如何从以下列表中随机检索项目?
foo = ['a', 'b', 'c', 'd', 'e']
原文由 Ray 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您想从列表中随机选择多个项目,或从一组中选择一个项目,我建议您改用 random.sample
。
import random
group_of_items = {'a', 'b', 'c', 'd', 'e'} # 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]
但是,如果您只是从列表中提取单个项目,那么选择就不那么笨拙了,因为使用示例的语法是 random.sample(some_list, 1)[0]
而不是 random.choice(some_list)
。
不幸的是,选择仅适用于序列(例如列表或元组)的单个输出。虽然 random.choice(tuple(some_set))
可能是从集合中获取单个项目的选项。
编辑:使用秘密
正如许多人指出的那样,如果您需要更安全的伪随机样本,您应该使用 secrets 模块:
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
group_of_items = {'a', 'b', 'c', 'd', 'e'} # 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]
编辑:Pythonic 单线
如果你想要一个更 pythonic 的单行来选择多个项目,你可以使用解包。
import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)
原文由 Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
使用
random.choice()
:对于 加密安全 的随机选择(例如,从单词列表生成密码),使用
secrets.choice()
:secrets
是 Python 3.6 中的新功能。在旧版本的 Python 上,您可以使用random.SystemRandom
类: