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

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

当前回答

使用random.choice():

import random

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

对于加密安全的随机选择(例如,从单词列表生成密码),请使用secrets.choice():

import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))

Python 3.6中的新秘密。在旧版本的Python上,可以使用random.SystemRandom类:

import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

其他回答

使用random.choice():

import random

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

对于加密安全的随机选择(例如,从单词列表生成密码),请使用secrets.choice():

import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))

Python 3.6中的新秘密。在旧版本的Python上,可以使用random.SystemRandom类:

import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

你可以:

from random import randint

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

print(foo[randint(0,4)])

随机项目选择:

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

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

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])