我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。
字典看起来像{'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'
通过随机调用。选择字典的键(国家)。
其他回答
试试这个:
import random
a = dict(....) # a is some dictionary
random_key = random.sample(a, 1)[0]
这绝对有效。
如果你不想使用random.choice(),你可以尝试这样做:
>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'
试试这个(使用随机。物品选择)
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'
因为最初的帖子想要一对:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))
(python 3风格)
下面是一个字典类的Python代码,它可以在O(1)时间内返回随机键。(为了可读性,我在代码中包含了myypy类型):
from typing import TypeVar, Generic, Dict, List
import random
K = TypeVar('K')
V = TypeVar('V')
class IndexableDict(Generic[K, V]):
def __init__(self) -> None:
self.keys: List[K] = []
self.vals: List[V] = []
self.dict: Dict[K, int] = {}
def __getitem__(self, key: K) -> V:
return self.vals[self.dict[key]]
def __setitem__(self, key: K, val: V) -> None:
if key in self.dict:
index = self.dict[key]
self.vals[index] = val
else:
self.dict[key] = len(self.keys)
self.keys.append(key)
self.vals.append(val)
def __contains__(self, key: K) -> bool:
return key in self.dict
def __len__(self) -> int:
return len(self.keys)
def random_key(self) -> K:
return self.keys[random.randrange(len(self.keys))]