从集合中随机选择?Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15837729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
random.choice from set? python
提问by jamyn
I'm working on an AI portion of a guessing game. I want the AI to select a random letter from this list. I'm doing it as a set so I can easily remove letters from the list as they are guessed in the game and are therefore no longer available to be guessed again.
我正在研究猜谜游戏的人工智能部分。我希望 AI 从这个列表中随机选择一个字母。我将它作为一个集合进行,因此我可以轻松地从列表中删除字母,因为它们在游戏中被猜到了,因此不再可以被再次猜到。
it says setobject isn't indexable. How can I work around this?
它说set对象不可索引。我该如何解决这个问题?
import random
aiTurn=True
while aiTurn == True:
allLetters = set(list('abcdefghijklmnopqrstuvwxyz'))
aiGuess=random.choice(allLetters)
print (aiGuess)
采纳答案by NPE
>>> random.sample(set('abcdefghijklmnopqrstuvwxyz'), 1)
['f']
Documentation: https://docs.python.org/3/library/random.html#random.sample
文档:https: //docs.python.org/3/library/random.html#random.sample
回答by Scott Ritchie
You should use random.choice(tuple(myset)), because it's faster and arguably cleaner looking than random.sample. I wrote the following to test:
您应该使用random.choice(tuple(myset)),因为它比random.sample. 我写了以下内容进行测试:
import random
import timeit
bigset = set(random.uniform(0,10000) for x in range(10000))
def choose():
random.choice(tuple(bigset))
def sample():
random.sample(bigset,1)[0]
print("random.choice:", timeit.timeit(choose, setup="global bigset", number=10000)) # 1.1082136780023575
print("random.sample:", timeit.timeit(sample, setup="global bigset", number=10000)) # 1.1889629259821959
From the numbers it seems that random.sampletakes 7% longer.
从数字来看,这似乎random.sample需要多花 7% 的时间。

