【问题标题】:Combining elements of two lists as key:value pairs in a dictionary goes wrong. Python 3x将两个列表的元素组合为字典中的键:值对会出错。蟒蛇 3x
【发布时间】:2018-05-13 12:58:02
【问题描述】:

我有两个列表:

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}

怎么做?为什么索引发生了变化?

【问题讨论】:

  • 字典不承诺保持秩序。
  • 索引是指订购吗? dict 不保留排序。如果您需要订购字典,请使用collections.OrderedDict
  • @Tuwuh 这行得通!我不知道。您可以将其更新为答案

标签: python python-3.x list dictionary python-3.5


【解决方案1】:

您可能会注意到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)])

【讨论】:

    【解决方案2】:

    索引是指排序吗? 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)])
    

    【讨论】:

      【解决方案3】:

      字典的索引没有顺序: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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2015-10-24
        • 1970-01-01
        相关资源
        最近更新 更多