将嵌套列表中的每个元素与另一个嵌套列表中的所有元素连接起来

Concatenate each element in a nested list with all elements in another nested list

鉴于下面的 2 个嵌套列表,其中 list1 的长度可能大于 list2 的长度,反之亦然。

我想将 list1 中的每个元素与 list2 中的所有其他元素相加。

List1 = [ 
      [2, 1],
      [1, 8]
    ]


List2 = [ 
      [1,2],
      [4,5],
      [2,6],
      [7,9]
    ]

----- 期望的结果-----

Result = [
      
      [2,1,1,2],
      [2,1,4,5],
      [2,1,2,6],
      [2,1,7,9],
      [1,8,1,2],
      [1,8,4,5],
      [1,8,2,6],
      [1,8,7,9]
     ]

我下面的尝试没有给出结果: 注意:每个嵌套列表的 len 都很大,任何一个列表的 len 都可以大于另一个。

import numpy as np

res = [(i+j).to_list() for i, j in zip(list1, list2)]

您可以使用 product 来自 itertools:

from itertools import product

[l1 + l2 for l1, l2 in product(List1, List2)]

结果:

[[2, 1, 1, 2], [2, 1, 4, 5], [2, 1, 2, 6], [2, 1, 7, 9], [1, 8, 1, 2], [1, 8, 4, 5], [1, 8, 2, 6], [1, 8, 7, 9]]
List1 = [ 
      [2, 1],
      [1, 8]
    ]

List2 = [ 
      [1,2],
      [4,5],
      [2,6],
      [7,9]
    ]

pairs = [(a, b) for a in List1 for b in List2]
  
concant = [x  + y for (x, y) in pairs]

result = []

for e in concant:
    result.append(e)

结果:

[[2, 1, 1, 2],

[2, 1, 4, 5],

[2, 1, 2, 6],

[2, 1, 7, 9],

[1, 8, 1, 2],

[1, 8, 4, 5],

[1, 8, 2, 6],

[1, 8, 7, 9]]