【问题标题】:concatenate two list of list with python用python连接两个列表列表
【发布时间】:2021-03-06 09:43:28
【问题描述】:

我有两个列表

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

我想将列表连接到

[[1,2,4],[5,3],[6,7,9]]

目标是如果列表中有相同的元素,它们将被连接起来。 非常感谢任何帮助。

【问题讨论】:

  • 如果列表像[[1,2], [2,3],[7,9]][[2,4], [6,7]]会输出什么
  • @Sociopath 必须是 [[1,2,3,4],[6,7,9]]
  • @Moch.ChamdaniM 正确

标签: python list concatenation


【解决方案1】:

这应该适用于更一般的情况:

def connected_components(list_of_lists):
    """ based on Howard's answer https://stackoverflow.com/a/4842897/10693596 """
    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)

或者也许以下是更 Pythonic 的版本:


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)

【讨论】:

  • 这似乎不适用于 cmets 中的第二个示例 :( 将“a”和“b”放在一个列表中似乎更好。
  • 我明白了,一般来说这是一个更难的问题,因为您实际上是在尝试在原始列表 a 中找到连接的组件,因此这里有几种解决方案:stackoverflow.com/questions/4842613/…
  • 我从链接到答案中加入了一个函数。
  • 好!我更新了我的答案,也用更短的方法来做。我会测试你的。
  • 如果情况是a = [[1,2],[5,3],[7,9]]b = [[2,4], [6,7], [9,3]],这两个代码都不起作用
【解决方案2】:

这是一个使用集合的解决方案: 它适用于 OP 示例以及 cmets 中给出的示例。

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]]

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    相关资源
    最近更新 更多