繁体   English   中英

将两个列表的元素组合为字典中的key:value对会出错。 Python 3x

[英]Combining elements of two lists as key:value pairs in a dictionary goes wrong. Python 3x

我有两个清单:

lists1 = [(0, 75), (75, 38), (38, 86), (86, 119), (119, 85), (85, 44), (44, 65), (65, 127)]
list2 = [12.0, 16.0, 17.0, 6.0, 31.0, 45.0, 13.0, 27.0]

两者的长度相同(8)

list_dict = dict(zip(list1,list2))

报告

{(0, 75): 12.0, (119, 85): 31.0, (86, 119): 6.0, (38, 86): 17.0, (44, 65): 13.0, (85, 44): 45.0, (75, 38): 16.0, (65, 127): 27.0}

我正在寻找的是

{(0, 75): 12.0, (75, 38): 16.0,(38, 86): 17.0,(86, 119): 6.0,(119, 85): 31.0,  (85, 44): 45.0, (44, 65): 13.0 , (65, 127): 27.0}

怎么做? 为什么索引已更改?

您可能会注意到, zip恰好与您的元素匹配。 这样只会使dictionary包含一些问题。 这实际上就是您问题的症结所在。

字典未订购! 这就是为什么当您打印出dictionary ,顺序可能会更改的原因。

因此,只需使用OrderedDict ,它就可以解决您的问题。

>>> from collections import OrderedDict
>>> d = OrderedDict(zip(l1, l2))
>>> d
=> OrderedDict([((0, 75), 12.0), ((75, 38), 16.0), ((38, 86), 17.0), ((86, 119), 6.0), ((119, 85), 31.0), ((85, 44), 45.0), ((44, 65), 13.0), ((65, 127), 27.0)])

所谓索引,是指订购吗? dict不保留排序。 如果需要有序字典,请使用collections.OrderedDict

from collections import OrderedDict
list_dict = OrderedDict(zip(lists1,list2))

那给了我:

>>> list_dict

OrderedDict([((0, 75), 12.0),
             ((75, 38), 16.0),
             ((38, 86), 17.0),
             ((86, 119), 6.0),
             ((119, 85), 31.0),
             ((85, 44), 45.0),
             ((44, 65), 13.0),
             ((65, 127), 27.0)])

字典的索引没有顺序: https : //docs.python.org/3/tutorial/datastructures.html#dictionaries

最好将字典视为无序的键集:值对[...]

在字典上执行list(d.keys())以任意顺序返回字典中使用的所有键的列表(如果要对其进行排序,请改用sorted(d.keys())

因此,当您需要按顺序遍历键时,只需对其排序即可:

>>> for k in sorted(list_dict.keys()): print k,list_dict[k]
... 
(0, 75) 12.0
(38, 86) 17.0
(44, 65) 13.0
(65, 127) 27.0
(75, 38) 16.0
(85, 44) 45.0
(86, 119) 6.0
(119, 85) 31.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM