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

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

当前回答

我们也可以使用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)

其他回答

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

from numpy.random import default_rng

rng = default_rng()
rng.choice(foo)

这可能已经是一个答案,但您可以使用random.shuffle。示例:

import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)

你可以:

from random import randint

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

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

如果还需要索引,请使用random.randrange

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

使用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))