我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。
字典看起来像{'VENEZUELA':'CARACAS'}
我该怎么做呢?
我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。
字典看起来像{'VENEZUELA':'CARACAS'}
我该怎么做呢?
当前回答
试试这个(使用随机。物品选择)
import random
a={ "str" : "sda" , "number" : 123, 55 : "num"}
random.choice(list(a.items()))
# ('str', 'sda')
random.choice(list(a.items()))[1] # getting a value
# 'num'
其他回答
我假设你在做一个类似测验的应用程序。对于这种应用程序,我写了一个函数,如下所示:
def shuffle(q):
"""
The input of the function will
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
current_selection = random.choice(q.keys())
if current_selection not in selected_keys:
selected_keys.append(current_selection)
i = i+1
print(current_selection+'? '+str(q[current_selection]))
如果我将输入问题={'委内瑞拉':'加拉加斯','加拿大':'多伦多'},并调用函数shuffle(问题),那么输出将如下:
VENEZUELA? CARACAS CANADA? TORONTO
您还可以通过调整选项进一步扩展此功能
试试这个:
import random
a = dict(....) # a is some dictionary
random_key = random.sample(a, 1)[0]
这绝对有效。
我写这篇文章是为了解决同样的问题:
https://github.com/robtandy/randomdict
它有O(1)对键、值和项的随机访问。
我通过寻找一个相当类似的解决方案找到了这篇文章。如果要从字典中选取多个元素,可以使用:
idx_picks = np.random.choice(len(d), num_of_picks, replace=False) #(Don't pick the same element twice)
result = dict ()
c_keys = [d.keys()] #not so efficient - unfortunately .keys() returns a non-indexable object because dicts are unordered
for i in idx_picks:
result[c_keys[i]] = d[i]
从字典集dict_data中选择50个随机键值:
sample = random.sample(set(dict_data.keys()), 50)