简体   繁体   中英

Combine each element from two lists of lists python

I've been struggling with this problem for a couple of hours and I can't seem to reach a solution. So I have two lists of lists in python:

list1=[['= 0\n', '= 1\n', '= 2\n', '= 3\n', '= 4\n'],['= 0\n', '= 1\n', '= 2\n']]
list2=[['a', 'b', 'c', 'd', 'e'],['a', 'b', 'c']]

and I want to combine these two lists of lists into something like:

[['a=0\n', 'b=1\n', 'c=2\n', 'd=3\n', 'e=4\n'], ['a=0\n', 'b=1\n', 'c=2\n']]

Basically, I want to take each element from the first list in list1 and append the first element from the first list in list2 and so on and keep the list of list structure.

Use a list comprehension with zip for pairing:

list1 = [['= 0\n', '= 1\n', '= 2\n', '= 3\n', '= 4\n'], ['= 0\n', '= 1\n', '= 2\n']]
list2 = [['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c']]

print([[(x+y) for x, y in zip(list2[i], list1[i])] for i in range(len(list1))])
# [['a= 0\n', 'b= 1\n', 'c= 2\n', 'd= 3\n', 'e= 4\n'], ['a= 0\n', 'b= 1\n', 'c= 2\n']]                                  

You can first zip the outer lists together, then zip those elementwise and concatenate them into a single string.

>>> [[b+a for a,b in zip(i,j)] for i,j in zip(list1, list2)]
[['a= 0\n', 'b= 1\n', 'c= 2\n', 'd= 3\n', 'e= 4\n'], ['a= 0\n', 'b= 1\n', 'c= 2\n']]

使用map的先前答案的变体:

list(map(lambda x: list(map(''.join, zip(*x))), zip(list2, list1)))

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