如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
如何从以下列表中随机检索项目?
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.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
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)
如果需要索引,只需使用:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]
random.choice也会这样做:)
你可以:
from random import randint
foo = ["a", "b", "c", "d", "e"]
print(foo[randint(0,4)])