如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
当前回答
这可能已经是一个答案,但您可以使用random.shuffle。示例:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)
其他回答
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)
我们也可以使用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)
简而言之,使用random.sample方法
示例方法返回一个新列表,其中包含总体中的元素,而保持原始总体不变。结果列表按选择顺序排列,因此所有子切片也将是有效的随机样本。
import random
lst = ['a', 'b', 'c', 'd', 'e']
random.seed(0) # remove this line, if you want different results for each run
rand_lst = random.sample(lst,3) # 3 is the number of sample you want to retrieve
print(rand_lst)
Output:['d', 'e', 'a']
这是运行代码https://onecompiler.com/python/3xem5jjvz
如果您想从列表中随机选择多个项目,或者从集合中选择一个项目,我建议使用random.sample。
import random
group_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
如果您只从列表中提取一个项目,那么choice就不那么麻烦了,因为使用sample将使用语法random.sample(some_list,1)[0],而不是random.cochoice(some_list)。
不幸的是,选择只适用于序列(如列表或元组)的单个输出。尽管随机。choice(tuple(some_set))可能是从集合中获取单个项的选项。
编辑:使用秘密
正如许多人所指出的,如果您需要更安全的伪随机样本,您应该使用secrets模块:
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
group_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
编辑:Pythonic One Liner
如果你想要一个更像蟒蛇的一行程序来选择多个项目,你可以使用解包。
import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)
我建议使用一个脚本来删除列表中随机选取的项目,直到列表为空:
维护一个集合并删除随机选取的元素(有选择),直到列表为空。
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([])