如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
当前回答
如果需要索引,只需使用:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]
random.choice也会这样做:)
其他回答
从Python 3.6开始,您可以使用secrets模块,对于加密或安全用途,它比随机模块更好。
要打印列表中的随机元素:
import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))
要打印随机索引:
print(secrets.randbelow(len(foo)))
有关详细信息,请参见PEP 506。
推荐的numpy方式是使用显式RNG:
from numpy.random import default_rng
rng = default_rng()
rng.choice(foo)
如果还需要索引,请使用random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
这是带有定义随机索引的变量的代码:
import random
foo = ['a', 'b', 'c', 'd', 'e']
randomindex = random.randint(0,len(foo)-1)
print (foo[randomindex])
## print (randomindex)
这是没有变量的代码:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print (foo[random.randint(0,len(foo)-1)])
这是最短最聪明的代码:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
(python 2.7)
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)