Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: merge nested lists

beginner to python here.

I have 2 nested lists that I want to merge:

list1 = ['a',
         (b, c),
         (d, e),
         (f, g, h) ]

list2 = [(p,q),
         (r, s),
         (t),
         (u, v, w) ]

the output I am looking for is:

list3 = [(a, p, q),
         (b, c, r, s),
         (d, e, t),
         (f, g, h, u, v, w) ]

Can this be done without any external libraries? note: len(list1) = len(list2)

like image 934
Rishav Sharan Avatar asked Oct 18 '11 11:10

Rishav Sharan


People also ask

How do I merge two nested lists in Python?

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.

How do you merge lists in Python?

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.


2 Answers

Use the power of the zip function and list comprehensions:

list1 = [('a', ),
        ('b', 'c'),
        ('d', 'e'),
        ('f', 'g', 'h') ]

list2 = [('p', 'q'),
        ('r', 's'),
        ('t', ),
        ('u', 'v', 'w') ]

print [a + b for a, b in zip(list1, list2)]
like image 188
Petr Viktorin Avatar answered Oct 08 '22 14:10

Petr Viktorin


from operator import add
list3 = map(add, list1, list2)
like image 41
John La Rooy Avatar answered Oct 08 '22 12:10

John La Rooy