如何从以下列表中随机检索项目?

foo = ['a', 'b', 'c', 'd', 'e']

当前回答

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

其他回答

从Python 3.6开始,您可以使用secrets模块,对于加密或安全用途,它比随机模块更好。

要打印列表中的随机元素:

import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))

要打印随机索引:

print(secrets.randbelow(len(foo)))

有关详细信息,请参见PEP 506。

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)

推荐的numpy方式是使用显式RNG:

from numpy.random import default_rng

rng = default_rng()
rng.choice(foo)

简而言之,使用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

随机项目选择:

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