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

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}

怎么做?为什么索引变了?

词典索引无序:https://docs.python.org/3/tutorial/datastructures.html#dictionaries

It is best to think of a dictionary as an unordered set of key: value pairs [...]

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead)

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

>>> 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

您可能会注意到 zip 与您的元素匹配得很好。所以只剩下 dictionary 包含一些问题。这实际上是您问题的症结所在。

字典没有排序! 这就是为什么当你打印你的 dictionary 时,顺序 可能 [=24] =]改变。

所以只需使用 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)])