【问题标题】:Convert a list and list of list to a dict in python将列表和列表列表转换为python中的dict
【发布时间】:2016-03-21 06:09:04
【问题描述】:

我有两个列表 ['a', 'b', 'c'][[1,2,3], [4,5,6]]

我期望在不使用 for 循环的情况下输出 {'a':[1,4], 'b':[2,5], 'c':[3,6]}

【问题讨论】:

    标签: python list python-2.7 dictionary


    【解决方案1】:

    使用zip

    >>> l1 = ['a', 'b', 'c']
    >>> l2 = [[1,2,3], [4,5,6]]
    >>> dict(zip(l1, zip(*l2)))  # zip(*l2) => [(1, 4), (2, 5), (3, 6)]
    {'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}
    

    更新

    如果你想得到字符串列表映射,使用dict comprehension:

    >>> {key:list(value) for key, value in zip(l1, zip(*l2))}
    {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}
    

    【讨论】:

    • 非常感谢您的回答。
    • @BurhanKhalid,你是对的。我更新了答案以添加返回字符串列表映射的不同版本。感谢您指出这一点。
    • @user3355648:如果您认为此答案有帮助,请记住将此答案标记为已接受。请看:How does accepting an answer work?
    【解决方案2】:

    正如在另一个答案中所说,您可能应该使用 zip。但是,如果您想避免使用其他第三方库,您可以通过在每个元素上调用 for 循环并手动添加到您的字典来手动完成。

    【讨论】:

      【解决方案3】:

      没有 for 循环。

      list1 = ['a', 'b', 'c']
      list2 = [[1,2,3], [4,5,6]]
      flat = reduce(lambda x,y: x+y,list2)
      d = {}
      df = dict(enumerate(flat))
      
      def create_dict(n):
        position = flat.index(df[n])%len(list1)
        if list1[position] in d.keys():
           d[list1[position]].append(df[n])
        else:
           d[list1[position]] = [df[n]]
      
      map( create_dict, df)
      print d
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-04
        • 2018-05-28
        • 1970-01-01
        • 2018-10-14
        相关资源
        最近更新 更多