如何从列表中随机选择一个项目? [英] How to randomly select an item from a list?
本文介绍了如何从列表中随机选择一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下列表:
foo = ['a', 'b', 'c', 'd', 'e']
从此列表中随机检索商品的最简单方法是什么?
What is the simplest way to retrieve an item at random from this list?
推荐答案
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
对于密码学上安全的随机选择(例如,用于从单词列表生成密码短语),请使用 secrets.choice()
For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()
import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
secrets
是Python 3.6中的新功能,在旧版本的Python上,您可以使用
secrets
is new in Python 3.6, on older versions of Python you can use the random.SystemRandom
class:
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
这篇关于如何从列表中随机选择一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文