manxing
manxing

Reputation: 3335

merge two lists python

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

Answers (7)

John Vinyard
John Vinyard

Reputation: 13515

This seems clear to me:

[x + (b[i],) for i,x in enumerate(a)]

Upvotes: 1

tobias_k
tobias_k

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

Achim
Achim

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

Prabhu Murthy
Prabhu Murthy

Reputation: 9271

print((a[0]+(b[0],),a[1]+(b[1],)))

Upvotes: 1

millimoose
millimoose

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

Joran Beasley
Joran Beasley

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

begemotv2718
begemotv2718

Reputation: 868

Try

map ( lambda x: x[0]+(x[1],), zip(a,b))

Upvotes: 3

Related Questions