Python | Combining nested lists

Python Methods and Functions

Examples :

  Input:  lst1 = [[5, 9], [8, 2, 6], [3, 4] ] lst2 = [[9, 5, 8], [2, 6], [3, 4, 1]]  Output:  [[9, 5], [8], [2, 6 ], [3, 4], [1]]  Input:  lst1 = [['a',' b', 'c'], [' x']] lst2 = [['b ',' c', 'y'], [' x', 'y']]  Output:  [[' b', 'c'], [' x'], ['y '], [' a']] 

Approach # 1: by setting the intersection with functools.reduce ()

This method uses an intersection set to compute each intersection, and then adds any remaining element (that is, elements that only appear in one of the two lists). First we will use functools.reduce () to get unique elements & # 39; lst1 & # 39; and & # 39; lst2 & # 39; and save them to & # 39; temp1 & # 39; and & # 39; temp2 & # 39; respectively. Then find the intersection of the sets of both lists in & # 39; lst3 & # 39 ;. Finally, find the symmetrical difference & # 39; lst1 & # 39; and & # 39; lst2 & # 39; which gives elements that only appear in one of the 2 sets and add that to & # 39; lst3 & # 39 ;.

# Python3 program for finding the most common
# intersection of two nested lists

import itertools

import functools

 

def GCI (lst1, lst2):

 

  temp1 = functools. reduce ( lambda a, b: set (a) .union ( set (b)), lst1)

temp2 = functools. reduce ( lambda a, b: set (a) .union ( set (b)), lst2)

 

lst3 = [ list ( set (a) .intersection ( set (b))) 

  for a, b in itertools.product (lst1, lst2) 

if len ( set (a ) .intersection ( set (b)))! = 0 ]

 

lst3.extend ([x] for x in temp1.symmetric_difference (temp2))

 

return lst3

  
# Driver code

lst1 = [[ 5 , 9 ], [ 8 , 2 , 6 ], [ 3 , 4 ]]

lst2 = [[ 9 , 5 , 8 ], [ 2 , 6 ], [ 3 , 4 , 1 ]]

print (GCI (lst1, lst2))

Output:

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

Approach # 2 : by setting an intersection using the filter

This is an efficient approach compared to approach # 1 because it makes intersection easier. Flatten the nested lists first. Take the intersection with filter () and store it in & # 39; lst3 & # 39 ;. Now find items not in lst1 or lst2 and store them in & # 39; temp & # 39 ;. Finally, add temp to lst3.

# Python3 program for finding the most common
# intersection two nested lists

import itertools

from functools import reduce

 

def GCI (lst1 , lst2):

 

temp1 = reduce ( list .__ add__, lst1)

  temp2 = reduce ( list .__ add__, lst2)

lst3 = list ( filter ( None , [ list ( set (o1) & amp;  set (o2))

for o1 in lst1 for o2 in lst2])) 

  

  temp = filter ( lambda x: x not in temp1 or x not in temp2,

  set (temp1) |  set (temp2))

lst3.append ( list (temp))

 

return lst3

 
# Driver code

lst1 = [[ 5 , 9 ], [ 8 , 2 , 6 ], [ 3 , 4 ]]

lst2 = [[ 9 , 5 , 8 ], [ 2 , 6 ], [ 3 , 4 , 1 ]]

print (GCI (lst1, lst2))

Exit:

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




Tutorials