import random as random
random.seed(0) # don't use seed function, if you want different results in each run
print(random.sample(foo,3)) # 3 is the number of sample you want to retrieve
Output:['d', 'e', 'a']
6
我这样做是为了让它起作用:
import random
pick = ['Random','Random1','Random2','Random3']
print (pick[int(random.random() * len(pick))])
import random
group_of_items = {1, 2, 3, 4} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
group_of_items = {1, 2, 3, 4} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]
15 回答
这是带有定义随机索引的变量的代码:
这是没有变量的代码:
这是最简单,最智能的代码:
(python 2.7)
在python 2中:
在python 3中:
我们也可以使用randint来做到这一点 .
一个简单的解决方案,如果你正在寻找这样的东西:
我希望您觉得这个解决方案很有帮助 .
从Python 3.6开始,您可以使用secrets模块,该模块比random模块更适用于加密或安全用途 .
要从列表中打印随机元素:
要打印随机索引:
有关详细信息,请参阅PEP 506 .
如果您还需要索引,请使用random.randrange
我提出了一个脚本,用于从列表中删除随机拾取的项目,直到它为空:
保持
set
并删除随机拾取的元素(使用choice
),直到列表为空 .三次运行给出三个不同的答案:
以下代码演示了是否需要生成相同的项目 . 您还可以指定要提取的样本数 .
sample
方法返回一个包含来自总体的元素的新列表,同时保持原始总体不变 . 结果列表按选择顺序排列,因此所有子切片也将是有效的随机样本 .我这样做是为了让它起作用:
如果你需要索引只需使用:
random.choice做同样的事:)
如果你想接近 truly random ,那么我建议使用
random
模块中的SystemRandom
对象和choice
方法:现在:
如果需要确定性伪随机选择,请使用
choice
函数(实际上是Random
对象上的绑定方法):这似乎是随机的,但实际上并非如此,如果我们重复重复它,我们可以看到它:
如果您想从列表中随机选择多个项目,或从集合中选择一个项目,我建议您改用
random.sample
.如果您只从列表中提取单个项目,则选择不那么笨重,因为使用示例将使用语法
random.sample(some_list, 1)[0]
而不是random.choice(some_list)
.不幸的是,选择仅适用于序列的单个输出(例如列表或元组) . 虽然
random.choice(tuple(some_set))
可能是从集合中获取单个项目的选项 .EDIT: Using Secrets
正如许多人所指出的,如果你需要更安全的伪随机样本,你应该使用秘密模块:
numpy
解决方案:numpy.random.choice对于这个问题,它的作用与接受的答案(
import random; random.choice()
)相同,但是我添加了它,因为程序员可能已经导入numpy
(像我一样)并且还有some differences between the two methods可能与您的实际用例有关 .为了重现性,您可以:
对于 one or more items 的样本,以
array
形式返回,传递size
参数:使用random.choice:
对于加密安全随机选择(例如,用于从词列表生成密码短语),请使用random.SystemRandom class: