首页 > 解决方案 > How to randomly select two elements of a python list?

问题描述

mylist = ['a','b','c','d']

How can I index the list so that I choose only two of the four elements? mylist[] throws all sorts of errors depending what datatype I put in the square brackets for indexing

标签: pythonlistindexing

解决方案


You can use random.sample Try this:

import random
mylist = ['a','b','c','d']

print(random.sample(mylist, 2))

推荐阅读