Esse Ti Esse Ti -4 years ago 107
Python Question

Python: Join each element different lists of lists in one list of lists

I would like to join the same index elements of many different lists of lists and obtaining a list of lists of the joined elements.
The lists always have the same length. Here is an example much simpler to understand.

list1 = [[1, 0], [1, 0], [1, 0], [0, 1]]

list2 = [[2, 1], [2, 1], [1, 2], [3, 2]]

Results I would like to obtain:

LIST = [[1,0,2,1],[1,0,2,1],[1,0,1,2],[0,1,3,2]]

Any help would be really appreciated.

Answer Source

Use a list comprehension:

Result = [item1 + item2 for item1, item2 in zip(list1, list2)]

It's is the same thing as this:

Result = []
for item1, item2 in zip(list1, list2):
    Result.append(item1 + item2)

If you feel like this line is too long and a bit cumbersome, try this:

from operator import add

Result = list(map(add, zip(list1, list2)))

If you're using Python 2.x, you can safely get rid of the call to list in this example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download