【问题标题】:Is there a way to combine elements from one "list of list" with another "list of list", having same element but different list length [duplicate]有没有办法将一个“列表列表”中的元素与另一个“列表列表”中的元素组合在一起,具有相同的元素但列表长度不同[重复]
【发布时间】:2024-04-20 00:25:02
【问题描述】:

我正在尝试根据它们之间的共同元素组合 2 个不同的列表列表(如果存在)

说,

list1 = [['a1', 'a2', 'b2'], ['h1', 'h2'], ['c1', 'd5']]
list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]

我需要一个结果列表,对于常见的元素 id “a2”或“c1”。从两个列表中,我们得到

combinedList = [['a1', 'a2', 'b2', 'b5'], ['d1', 'd2', 'c1', 'd3', 'd5'], ['h1', 'h2']]

尝试和失败:
我曾尝试使用 NetworkX Graph 传递列表,但徒劳无功,因为它们包含不同的长度。还尝试对列表列表进行排序并尝试根据第一个元素进行分组,但这也不起作用。

【问题讨论】:

    标签: python arrays python-3.x list graph


    【解决方案1】:

    试试这个方法:-

    list1 = [['a1', 'a2', 'b2'], ['c1', 'd5']]
    list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]
    combined_list=[]
    for i in range(len(list1)): # or len(list2) also works
        combined_list.append(list1[i]+list2[i])
    print(combined_list)
    

    输出:

    [['a1', 'a2', 'b2', 'b5', 'a2'], ['c1', 'd5', 'd1', 'd2', 'c1', 'd3']]
    

    要删除重复项,您只需执行以下操作:-

    list1 = [['a1', 'a2', 'b2'], ['c1', 'd5']]
    list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]
    combined_list=[]
    for i in range(len(list1)): # or len(list2) also works
        combined_list.append(list(set(list1[i]+list2[i])))
    print(combined_list)
    

    【讨论】:

    • 谢谢!如果两个列表都包含相同的长度,则效果很好。如果长度不同,假设列表 1 包含附加元素 ``` list1 = [['a1', 'a2', 'b2'], ['c1', 'd5'],['h1','h2' ] ``` 解决方案失败。无论如何,非常感谢您的帮助