我刚刚开始使用 Python(VBA 背景)。为什么这本字典的创建顺序是乱的?不应该是a:1、b:2...等等吗?
class Card:
def county(self):
c = 0
l = 0
groupL = {} # groupL for Loop
for n in range(0,13):
c += 1
l = chr(n+97)
groupL.setdefault(l,c)
return groupL
pick_card = Card()
group = pick_card.county()
print group
这是输出:
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12}
或者,它只是打印得乱序?
python 中的字典没有顺序。换句话说,当您迭代字典时,“产生”键/项目的顺序并不是您将它们放入字典中的顺序。 (在不同版本的 python 上尝试您的代码,您可能会得到不同顺序的输出)。如果你想要一本有序的字典,你需要一个collections.OrderedDict
直到 python 2.7 才引入。您可以在以下位置找到等效的食谱ActiveState
如果您使用的是旧版本的 python。然而,通常只需对项目进行排序就足够了(例如sorted(mydict.items())
.
EDIT根据要求,一个 OrderedDict 示例:
from collections import OrderedDict
groupL = OrderedDict() # groupL for Loop
c = 0
for n in range(0,13):
c += 1
l = chr(n+97)
groupL.setdefault(l,c)
print (groupL)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)