如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
当前回答
随机项目选择:
import random
my_list = [1, 2, 3, 4, 5]
num_selections = 2
new_list = random.sample(my_list, num_selections)
要保持列表的顺序,可以执行以下操作:
randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]
的副本https://stackoverflow.com/a/49682832/4383027
其他回答
我们也可以使用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
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)
随机项目选择:
import random
my_list = [1, 2, 3, 4, 5]
num_selections = 2
new_list = random.sample(my_list, num_selections)
要保持列表的顺序,可以执行以下操作:
randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]
的副本https://stackoverflow.com/a/49682832/4383027
推荐的numpy方式是使用显式RNG:
from numpy.random import default_rng
rng = default_rng()
rng.choice(foo)
NumPy解决方案:NumPy.random.ochoice
对于这个问题,它的工作原理与接受的答案(import random;random.choice())相同,但我添加了它,因为程序员可能已经(像我一样)导入了NumPy
此外,这两种方法之间也存在一些差异,可能与您的实际用例有关。
import numpy as np
np.random.choice(foo) # randomly selects a single item
为了再现性,您可以执行以下操作:
np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'
对于作为数组返回的一个或多个项目的示例,请传递size参数:
np.random.choice(foo, 5) # sample with replacement (default)
np.random.choice(foo, 5, False) # sample without replacement