【问题标题】:Dict Comprehension python from list of lists列表列表中的字典理解python
【发布时间】:2018-03-18 15:26:21
【问题描述】:

我有一个列表列表,我正在尝试从列表中制作字典。我知道如何使用这种方法来做到这一点。 Creating a dictionary with list of lists in Python

我要做的是使用第一个列表中的元素作为键来构建列表,其余具有相同索引的项目将是值列表。但我不知道从哪里开始。每个列表的长度相同,但列表的长度不同

exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]

resultDict = {'first':['A','1'],'second':['B','2'],'third':['C','3']}

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    解包并使用zip 后跟一个dict 理解来获取第一个元素的映射似乎是可读的。

    result_dict = {first: rest for first, *rest in zip(*exampleList)}
    

    【讨论】:

      【解决方案2】:

      使用zip(*exampleList) 解压值并使用键值对创建字典。

      dicta = {k:[a, b] for k, a, b in zip(*exampleList)}
      print(dicta)
      # {'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
      

      如果更多列表:

      dicta = {k:[*a] for k, *a in zip(*exampleList)}
      # {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
      

      【讨论】:

        【解决方案3】:

        注意exampleList 可以是任意长度的情况..

        exampleList = [['first','second','third'],['A','B','C'], ['1','2','3'],[4,5,6]]
        
        z=list(zip(*exampleList[1:]))
        d={k:list(z[i])  for i,k in enumerate(exampleList[0])}
        print(d)
        

        输出

        {'first': ['A', '1', 4], 'second': ['B', '2', 5], 'third': ['C', '3', 6]}
        

        【讨论】:

        • 我只是将其添加到说明中,因为列表的长度可能会有所不同。
        【解决方案4】:

        如果您不关心列表与元组,那么就像使用两次zip 一样简单:

        result_dict = dict(zip(example_list[0], zip(*example_list[1:])))
        

        否则,您需要致电map

        result_dict = dict(zip(example_list[0], map(list, zip(*example_list[1:]))))
        

        【讨论】:

          【解决方案5】:

          zip 函数可能正是您想要的。

          exampleList = [['first','second','third'],['A','B','C'], ['1','2','3']]
          d = {x: [y, z] for x, y, z in zip(*exampleList)}
          print(d)
          #{'first': ['A', '1'], 'second': ['B', '2'], 'third': ['C', '3']}
          

          【讨论】:

            猜你喜欢
            • 2011-03-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-18
            • 1970-01-01
            • 2022-11-22
            • 2023-02-15
            相关资源
            最近更新 更多