我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。
字典看起来像{'VENEZUELA':'CARACAS'}
我该怎么做呢?
我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。
字典看起来像{'VENEZUELA':'CARACAS'}
我该怎么做呢?
当前回答
>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'
通过随机调用。选择字典的键(国家)。
其他回答
我假设你在做一个类似测验的应用程序。对于这种应用程序,我写了一个函数,如下所示:
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
您还可以通过调整选项进一步扩展此功能
从字典集dict_data中选择50个随机键值:
sample = random.sample(set(dict_data.keys()), 50)
>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'
通过随机调用。选择字典的键(国家)。
当他们要求随机配对时,他们指的是键和值。
对于这样一个字典,其中的关键:价值观是国家:城市,
使用random.choice()。
将字典键传递给这个函数,如下所示:
import random
keys = list(my_dict)
country = random.choice(keys)
你可能希望跟踪在一轮中已经被调用的键,当获得一个新的国家时,循环直到随机选择不在那些已经“抽取”的列表中……只要绘制的列表比键列表短。
一种方法是:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))
编辑:在最初的帖子发布几年后,这个问题被修改了,现在是一对,而不是一个。最后一行现在应该是:
country, capital = random.choice(list(d.items()))