简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM