首页 > Python > 如何从以下列表中随机检索项目?

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

上一篇 下一篇

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

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

分割线

网友回答:

如果您想从列表中随机选择多个项目,或从集合中选择一个项目,我建议您改用。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] 

但是,如果您只从列表中拉取单个项目,则选择不那么笨拙,因为使用 sample 将具有语法而不是 .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 one-Liner

如果你想要一个更pythonic的单行来选择多个项目,你可以使用解包。

import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 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))

分割线

网友回答:

如果还需要索引,请使用random.randrange

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])

模板简介:该模板名称为【如何从以下列表中随机检索项目?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 256次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 02-17
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信公众平台 微信模板 微信素材 微信文章 微信图片 自适应 单页式简历模板 html5 响应式 企业网站
您可能会喜欢的其他模板