dws*_*ein 7 python dictionary for-loop setdefault
我刚开始玩Python(VBA背景).为什么这本字典无序创建?不应该是: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
Run Code Online (Sandbox Code Playgroud)
这是输出:
{'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}
Run Code Online (Sandbox Code Playgroud)
或者,它是否只是打印失序?
mgi*_*son 17
字典在python中没有顺序.换句话说,当您遍历字典时,键/项"被放弃"的顺序不是您将它们放入字典的顺序.(在不同版本的python上尝试你的代码,你可能得到不同的有序输出).如果你想要一个有序的字典,你需要一个collections.OrderedDict直到python 2.7才引入的字典.ActiveState如果您使用的是旧版本的python ,则可以找到相应的配方.但是,通常只对物品进行分类就足够了(例如sorted(mydict.items()).
按要求编辑,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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10234 次 |
| 最近记录: |