Assume I have the following list:
(假设我有以下列表:)
foo = ['a', 'b', 'c', 'd', 'e']
What is the simplest way to retrieve an item at random from this list?
(从此列表中随机检索项目的最简单方法是什么?)
Use random.choice()
random.choice()
(使用random.choice())
import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo))
For cryptographically secure random choices (eg for generating a passphrase from a wordlist), use random.SystemRandom class
random.SystemRandom
(对于加密安全的随机选择(例如,用于从单词列表生成密码短语),请使用random.SystemRandom类)
import random foo = ['battery', 'correct', 'horse', 'staple'] secure_random = random.SystemRandom() print(secure_random.choice(foo))
or secrets.choice()
secrets.choice()
(或secrets.choice())
import secrets foo = ['a', 'b', 'c', 'd', 'e'] print(secrets.choice(foo))
2.1m questions
2.1m answers
60 comments
57.0k users