【发布时间】:2012-07-31 20:39:54
【问题描述】:
我刚刚开始玩 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}
或者,它是否只是乱序打印?
【问题讨论】:
-
附带说明一下,为什么在这里使用 setdefault?在很多情况下这是一个有用的功能,但对于只是将内容插入字典,
groupL[l] = c可能是你想要的。
标签: python dictionary for-loop setdefault