Reputation: 295
I have some troubles in merging two list of lists to one. I think there is a simple solution, but I'm stuck for hours.
My two list of lists are for example:
a=[['1','2'],['3','4']]
b=[['5','6'],['7','8']]
And what I try to get is:
c=[['1','2','5','6'],['3','4','7','8']]
But I don't know how many rows and columns the lists have.
I tried to use the zip
command but it produced something like:
[(['1','2'],['5','6']),(['3','4'],['7','8'])]
Thanks very much for any help on this issue!!!
Maybe something like How can I add an additional row and column to an array? would work but I suppose there is an simpler solution.
Upvotes: 2
Views: 393
Reputation: 1138
If the two lists are of the same length, you could use a simple loop:
listone = [['1','2'],['3','4']]
listtwo = [['5','6'],['7','8']]
newlist = []
for i in range(0, len(data)):
newlist.append(listone[i] + listtwo[i])
print(newlist)
[['1','2','5','6'],['3','4','7','8']]
Upvotes: 0
Reputation: 6797
[sum(ai_bi, []) for ai_bi in zip(a, b)]
which scales to n lists of lists :
L = (a, b, ...)
[sum(el, []) for el in zip(*L)]
Upvotes: 0
Reputation: 133574
>>> a=[['1','2'],['3','4']]
>>> b=[['5','6'],['7','8']]
>>> [x + y for x, y in zip(a, b)]
[['1', '2', '5', '6'], ['3', '4', '7', '8']]
Upvotes: 2
Reputation: 143
If your lists have the same lenght:
c = []
for idx in range(len(a)):
c.append(a[idx]+b[idx])
Not very elegant though.
Upvotes: -1