Home > Enterprise >  Concatenate each element in a nested list with all elements in another nested list
Concatenate each element in a nested list with all elements in another nested list

Time:05-05

Given the 2 nested lists below where length of list1 could be > length of list2 and vice versa.

I want to add every elements in list1 with all other elements in list2.

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


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

----- Desired Results-----

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

My attempt below didn't give the results: Note: The len of each nested list is large and len of either list could be greater than the other.

import numpy as np

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

CodePudding user response:

You can use product from itertools:

from itertools import product

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

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

CodePudding user response:

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)

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