2024-04-25 10:01:01 发布
网友
我已经用python写下了这个程序
创建字典
a = { 'a':'b', 'x':'x', '2':'2' }
运行后循环
for c in a: a[c]
结果是
'2' 'b' 'x'
我想,应该有“b x 2”的结果,但它会自动排序,为什么会发生这种情况,我如何控制这种情况
python中的Dictionary没有顺序,您接收密钥的顺序基本上取决于python实现。您的代码不应该依赖于它
从documentation-
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)
如果顺序对程序很重要,请使用^{}。示例-
>>> from collections import OrderedDict >>> d = OrderedDict([('a','b'),('x','x'),('2','2')]) >>> for c in d: ... d[c] ... 'b' 'x' '2'
python中的Dictionary没有顺序,您接收密钥的顺序基本上取决于python实现。您的代码不应该依赖于它
从documentation-
如果顺序对程序很重要,请使用^{} 。示例-
相关问题 更多 >
编程相关推荐