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?
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)]
>>> 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)]
>>>
Try
map ( lambda x: x[0]+(x[1],), zip(a,b))
And yet another:
map(lambda t, e: t + (e,), a, b)
No need to zip and unpack; map can take both lists at once.
len(a) != len(b). map fills the excess with None and it'll blow up.zip?
ais a list of tuples. tuple is an immutable sequence type.