Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - 如何从列表中随机选择一个项目?(How to randomly select an item from a list?)

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?

(从此列表中随机检索项目的最简单方法是什么?)

  ask by Ray Vega translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use 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类)

import random

foo = ['battery', 'correct', 'horse', 'staple']
secure_random = random.SystemRandom()
print(secure_random.choice(foo))

or secrets.choice()

(或secrets.choice())

import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...