[英]How to iterate through dict in random order in Python?
如何以随机顺序遍历字典的所有项目? 我的意思是 random.shuffle,但对于字典。
dict
是一组无序的键值对。 当您迭代dict
,它实际上是随机的。 但是要显式地随机化键值对的序列,您需要使用不同的有序对象,例如列表。 dict.items()
、 dict.keys()
和dict.values()
每个返回列表,可以洗牌。
items=d.items() # List of tuples
random.shuffle(items)
for key, value in items:
print key, value
keys=d.keys() # List of keys
random.shuffle(keys)
for key in keys:
print key, d[key]
或者,如果您不关心密钥:
values=d.values() # List of values
random.shuffle(values) # Shuffles in-place
for value in values:
print value
您还可以“按随机排序”:
for key, value in sorted(d.items(), key=lambda x: random.random()):
print key, value
你不能。 使用.keys()
获取键列表,将它们.keys()
,然后在索引原始字典的同时遍历列表。
或者使用.items()
,然后对其进行洗牌和迭代。
import random
def main():
CORRECT = 0
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
'Arizona': 'Phoenix', 'Arkansas': 'Little Rock'} #etc... you get the idea of a dictionary
allstates = list(capitals.keys()) #creates a variable name and list of the dictionary items
random.shuffle(allstates) #shuffles the variable
for a in allstates: #searches the variable name for parameter
studentinput = input('What is the capital of '+a+'? ')
if studentinput.upper() == capitals[a].upper():
CORRECT += 1
main()
我想要一种快速遍历无序列表的方法,所以我写了一个生成器:
def shuffled(lis):
for index in random.sample(range(len(lis)), len(lis)):
yield lis[index]
现在,我可以在我的字典步d
像这样:
for item in shuffled(list(d.values())):
print(item)
或者如果你想跳过创建一个新函数,这里有一个 2-liner:
for item in random.sample(list(d.values()), len(d)):
print(item)
正如Charles Brunet已经说过的那样,字典是键值对的随机排列。 但是要使其真正随机,您将使用随机模块。 我已经编写了一个函数,它可以对所有键进行混洗,因此当您迭代它时,您将随机迭代。 看代码可以更清楚的理解:
def shuffle(q):
"""
This function is for shuffling
the dictionary elements.
"""
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
return selected_keys
现在,当您调用该函数时,只需传递参数(您要洗牌的字典的名称),您将获得一个洗牌的键列表。 最后,您可以为列表的长度创建一个循环,并使用name_of_dictionary[key]
来获取值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.