Reputation: 3335
I have two lists:
a = [(1,2,3),(4,5,6)]
b = [7,8]
I want to merge it into:
c = [(1,2,3,7),(4,5,6,8)]
I used zip(a,b)
but the result does not seem correct. Can anyone help?
Upvotes: 3
Views: 1678
Reputation: 13515
This seems clear to me:
[x + (b[i],) for i,x in enumerate(a)]
Upvotes: 1
Reputation: 82949
And yet another:
map(lambda t, e: t + (e,), a, b)
No need to zip and unpack; map
can take both lists at once.
Upvotes: 2
Reputation: 15722
And yet another version:
from itertools import izip
[x+(y,) for x,y in izip(a,b)]
Should be efficient and it expresses what you are really doing in a readable way.
Upvotes: 2
Reputation: 39990
zip()
will just pair up the tuples and the integers. You also need to concatenate the tuple and the new item:
c = [aa + (bb,)
for aa, bb in zip(a, b)]
Upvotes: 6
Reputation: 114098
>>> a = [(1,2,3),(4,5,6)]
>>> b = [7,8]
>>> c = zip(*a)+[b] #c looks like [(1,4),(2,5),(3,6),(7,8)]
>>> print zip(*c) #zip it back together
[(1, 2, 3, 7), (4, 5, 6, 8)]
>>>
Upvotes: 5