【问题标题】:merging sublists based on repeated values in another list根据另一个列表中的重复值合并子列表
【发布时间】:2019-08-11 15:31:03
【问题描述】:

我有 2 个列表,我想从中创建一个 dict。

我的list1是:

[1,2,2,3]

我的 list2 是:

[['A','B'],['J','K'],[L'','M'],['W','X']]

我想做一个

dict(zip(list1,list2))

但是鉴于 list1 有一个重复的键,我失去了一个键 2 及其值。

所以我想根据 list 1 中的重复值加入 list2 的子列表。

list1 和 list2 的索引顺序相同。

期望的输出是:

[['A','B'],['J','K','L','M'],['W','X']]

所以我可以删除 list1 的副本并制作

dict(zip(list1_without_dups,list2_merged_sublists))    

对不起,我没有包括我的尝试,但我一直在寻找类似的问题,但没有成功,不知道如何面对它。

【问题讨论】:

    标签: python list dictionary list-comprehension


    【解决方案1】:

    使用collections.defaultdict:

    from collections import defaultdict
    
    lst1 = [1,2,2,3]
    lst2 = [['A','B'],['J','K'],['L','M'],['W','X']]
    
    d = defaultdict(list)
    
    for x, y in zip(lst1, lst2):
        d[x].extend(y)
    
    print(d)
    

    哪个输出:

    defaultdict(<class 'list'>, {1: ['A', 'B'], 2: ['J', 'K', 'L', 'M'], 3: ['W', 'X']})
    

    您现在可以提取值以获得所需的列表。

    【讨论】:

      【解决方案2】:

      你可以使用itertools.groupby:

      from itertools import groupby as g, chain as c
      d =  [1,2,2,3]
      new_d = [['A','B'],['J','K'],['L','M'],['W','X']]
      r = [list(c(*[j for _, j in b])) for _, b in g(list(zip(d, new_d)), key=lambda x:x[0])]
      

      输出:

      [['A', 'B'], ['J', 'K', 'L', 'M'], ['W', 'X']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        • 1970-01-01
        • 2015-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多