使用Python将两个列表合并成一个列表。

3

我有两个嵌套列表

a = [[1,2],[5,3],[7,9]]
b = [[2,4], [6,7]]

我愿意将列表连接起来。
[[1,2,4],[5,3],[6,7,9]]

目标是将列表中相同的元素串联起来。非常感谢您的帮助。

4
如果列表分别为[[1,2],[2,3],[7,9]][[2,4],[6,7]],输出会是什么? - Sociopath
@Sociopath,它必须是[[1,2,3,4],[6,7,9]] - Moch. Chamdani M
@Moch.ChamdaniM 正确 - sein
2个回答

4
这应该适用于更一般的情况:
def connected_components(list_of_lists):
    """ based on Howard's answer https://dev59.com/Zm445IYBdhLWcg3wdqOO#4842897 """
    temp_list_copy = list_of_lists.copy()
    result = []
    while len(temp_list_copy)>0:
        first, *rest = temp_list_copy
        first = set(first)

        lf = -1
        while len(first)>lf:
            lf = len(first)

            rest2 = []
            for r in rest:
                if len(first.intersection(set(r)))>0:
                    first |= set(r)
                else:
                    rest2.append(r)     
            rest = rest2
        result.append(list(first))
        temp_list_copy = rest
    return result


a = [[1,2],[5,3],[7,9]]
b = [[2,4], [6,7]]

a = connected_components(a)
b = connected_components(b)

for n, i in enumerate(a):
    combined_list = a[n]+ [jj for j in b if set(j).intersection(set(i)) for jj in j]

    a[n] = sorted(list(set(combined_list)))

print(a)

或者以下也许是更符合Python语言特色的版本:


result = [
    sorted(
        set([
            k
            for j in b
            for k in (set(i)|set(j) if set(i)&set(j) else set(i))
        ])
    )
    for i in a
]
print(result)

1
这似乎对评论中的第二个示例不起作用 :( 最好将“a”和“b”放在一个列表中处理。 - Malo
好的!我更新了我的答案,还提供了一种更简短的方法。我会测试你的。 - Malo
如果情况是 a = [[1,2],[5,3],[7,9]]b = [[2,4], [6,7], [9,3]],那么这两个代码都无法工作。 - Moch. Chamdani M
当然,如果你想连接子列表,你可以再次运行 a = connected_components(a),我认为它会给出所需的结果。 - SultanOrazbayev
具体来说,对结果列表运行该函数以合并重叠的子列表。 - SultanOrazbayev
显示剩余2条评论

2
这里有一个与集合一起使用的解决方案: 它适用于OP示例以及评论中给出的示例。
a = [[1,2], [2,3],[7,9]]
b = [[2,4], [6,7]]     

a = a+b
b = []

while a != []:
    i = a.pop()
    for j in range(len(b)):
        if set(b[j]).intersection(set(i)) != set():
            b[j] = list(set(b[j]).union(set(i)))
            break
    else:
        if i != []:
            b.append(i)


print(b)
## [[9, 6, 7], [1, 2, 3, 4]]

其他测试:

a = [[8, 9], [1,2],[5,3],[7,9], [5, 6]]
b = [[2,4], [6,7]]
## [[3, 5, 6, 7, 8, 9], [1, 2, 4]]

a = [[1,2], [2,3],[7,9]]
b = [[2,4], [6,7]]
## [[9, 6, 7], [1, 2, 3, 4]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接