0

I am trying to combine 2 different lists of lists based on common elements between them if present

Say,

list1 = [['a1', 'a2', 'b2'], ['h1', 'h2'], ['c1', 'd5']]
list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]

I need a resultant list such that, for common element id "a2" or "c1". from both list, we get

combinedList = [['a1', 'a2', 'b2', 'b5'], ['d1', 'd2', 'c1', 'd3', 'd5'], ['h1', 'h2']]

Tried and Failed:
I have tried using NetworkX Graph to pass lists, but in vain as they contain different lengths. Also tried to sort the list of list and tried grouping based on first element and that too didn't work.

David Buck
  • 3,752
  • 35
  • 31
  • 35

1 Answers1

1

Try this way:-

list1 = [['a1', 'a2', 'b2'], ['c1', 'd5']]
list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]
combined_list=[]
for i in range(len(list1)): # or len(list2) also works
    combined_list.append(list1[i]+list2[i])
print(combined_list)

Output:

[['a1', 'a2', 'b2', 'b5', 'a2'], ['c1', 'd5', 'd1', 'd2', 'c1', 'd3']]

For removing duplicates you can simply do:-

list1 = [['a1', 'a2', 'b2'], ['c1', 'd5']]
list2 = [['b5', 'a2'], ['d1', 'd2', 'c1', 'd3']]
combined_list=[]
for i in range(len(list1)): # or len(list2) also works
    combined_list.append(list(set(list1[i]+list2[i])))
print(combined_list)
Bibhav
  • 1,579
  • 1
  • 5
  • 18
  • Thank you! It works well if both list contains same length. If lengths are different, say if list 1 contains additional element ``` list1 = [['a1', 'a2', 'b2'], ['c1', 'd5'],['h1','h2'] ``` the solution fails. Anyways Thanks a lot for your help – Ravi Shankar Nov 02 '21 at 11:14