如何从列表中随机选择一个项目?

新手上路,请多包涵

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

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

原文由 Ray 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 909
2 个回答

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

secrets 是 Python 3.6 中的新功能。在旧版本的 Python 上,您可以使用 random.SystemRandom 类:

 import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

原文由 Pēteris Caune 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题