如何在Python中以随机顺序遍历dict? [英] How to iterate through dict in random order in Python?
本文介绍了如何在Python中以随机顺序遍历dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以随机顺序遍历字典的所有项目?我的意思是random.shuffle,不过是字典.
How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
推荐答案
dict
是一组无序的键/值对.迭代dict
时,它实际上是随机的.但是要显式地随机化键值对的序列,您需要使用其他有序对象,例如列表. dict.items()
,dict.keys()
和dict.values()
每个返回列表都可以改组.
A dict
is an unordered set of key-value pairs. When you iterate a dict
, it is effectively random. But to explicitly randomize the sequence of key-value pairs, you need to work with a different object that is ordered, like a list. dict.items()
, dict.keys()
, and dict.values()
each return lists, which can be shuffled.
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]
或者,如果您不关心按键,则:
Or, if you don't care about the keys:
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
这篇关于如何在Python中以随机顺序遍历dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文