random.choice
输入应该是一个序列。这会导致 dict
出现奇怪的行为,它不是序列类型,但可以像下标一样:
>>> d = {0: 'spam', 1: 'eggs', 3: 'potato'}
>>> random.choice(d)
'spam'
>>> random.choice(d)
'eggs'
>>> random.choice(d)
'spam'
>>> random.choice(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
KeyError: 2
此外,
random.choice
在 set
以及 collections
模块中的一些其他容器上根本不起作用。
是否有充分的理由为什么
random.choice(d)
不应该以明显的方式工作,返回随机密钥?
我考虑过
random.choice(list(d))
和random.sample(d, 1)[0]
但希望可能有更有效的方法。可以在不降低序列当前行为的情况下改进random.choice
吗?
您可以在 2006 年的 Python bug 跟踪器上看到 this thread 关于 random.choice 不适用于集合。从算法上讲,可以使其以相同的渐近效率工作,但它需要 set/dict 数据结构的自定义支持,或者接口中的新方法。 python 开发人员认为不需要它。
如果您只想要字典中的顶层值,这是一个替代解决方案。
我相信如果你愿意的话,你可以吃火腿🥩。
这不是一个完美的解决方案,但它是一种解决方法,可以防止您出现奇怪的错误。我希望将来能够实现一种方法来实现这一点,并指定第 1、2、3 层等(对于嵌套字典)。
from random import choice
DictionaryOfItems = {'good': 'steak', 'salty': 'eggs', 'yummy': 'bacon', 'delicious': 'hashbrowns', 'tasty': 'orange juice'}
dictList = []
for i in DictionaryOfItems.keys(): # Create the dictionary list to choose from.
dictList.extend([i])
a = choice(dictList) # Set the choice.
b = DictionaryOfItems.get(a) # get he details of the dictionary item.
print(f"{a}: {b}") # print the name of the dict key & details.
# tasty: orange juice
print(f"{b}") # print the name of the selected dictionary value & details.
# orange juice
from random import choice
def getTopLevelDictionaryValues(dictionary):
if isinstance(dictionary, dict):
dictList = []
for i in DictionaryOfItems.keys(): # Create the dictionary list to choose from.
dictList.extend([i])
a = choice(dictList) # Set the choice.
b = DictionaryOfItems.get(a) # get he details of the dictionary item.
return a, b
DictionaryOfItems = {0: 'steak', 1: 'eggs', 2: 'bacon', 3: 'hashbrowns', 4: 'orange juice'}
a, b = getTopLevelDictionaryValues(DictionaryOfItems)
print(f"{a}: {b}") # print the name of the dict key & details.
# 3: hashbrowns
print(f"{b}") # print the name of the selected dictionary value & details.
# hashbrowns
DictionaryOfItems = {'good': 'steak', 'salty': 'eggs', 'yummy': 'bacon', 'delicious': 'hashbrowns', 'tasty': 'orange juice'}
a, b = getTopLevelDictionaryValues(DictionaryOfItems)
print(f"{a}: {b}") # print the name of the dict key & details.
# good: steak
print(f"{b}") # print the name of the selected dictionary value & details.
# steak