如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
当前回答
我通常使用随机模块处理列表和随机化:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
其他回答
我们也可以使用randint来实现这一点。
from random import randint
l= ['a','b','c']
def get_rand_element(l):
if l:
return l[randint(0,len(l)-1)]
else:
return None
get_rand_element(l)
foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1
在Python 2中:
random_items = random.sample(population=foo, k=number_of_samples)
在Python 3中:
random_items = random.choices(population=foo, k=number_of_samples)
我建议使用一个脚本来删除列表中随机选取的项目,直到列表为空:
维护一个集合并删除随机选取的元素(有选择),直到列表为空。
s=set(range(1,6))
import random
while len(s)>0:
s.remove(random.choice(list(s)))
print(s)
三次跑步给出三种不同的答案:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
你可以:
from random import randint
foo = ["a", "b", "c", "d", "e"]
print(foo[randint(0,4)])
这可能已经是一个答案,但您可以使用random.shuffle。示例:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)