Char
Char

Reputation: 1735

Zipping tuples and unpacking into same dimension

Given two lists

A = ['a','b','c','d']
B = [(1,11),(2,22),(3,33),(4,44)]

I want to zip into the list [('a', 1, 11), ('b', 2, 22), ('c', 3, 33), ('d', 4, 44)].

Doing list(zip(a, b)) gives [('a', (1, 11)), ('b', (2, 22)), ('c', (3, 33)), ('d', (4, 44))].

Unpacking B doesn't work [('a', 1, 2, 3, 4), ('b', 11, 22, 33, 44)].

Upvotes: 2

Views: 51

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

Or try map:

>>> list(map(lambda x,y: (x,)+y,A,B))
[('a', 1, 11), ('b', 2, 22), ('c', 3, 33), ('d', 4, 44)]

Upvotes: 1

Ilia Gilmijarow
Ilia Gilmijarow

Reputation: 1020

Although coldspeed's answer is much better, here is my 2 cents

l = [(z[0], z[1][0], z[1][1]) for z in zip (A, B)]
print(l)

Upvotes: 0

cs95
cs95

Reputation: 402483

With python3.6, you can zip them and use the unpacking operator:

>>> [(a, *b) for a, b in zip(A, B)]
[('a', 1, 11), ('b', 2, 22), ('c', 3, 33), ('d', 4, 44)]

For older versions, perform tuple concatenation...

>>> [(a, ) + b for a, b in zip(A, B)]
[('a', 1, 11), ('b', 2, 22), ('c', 3, 33), ('d', 4, 44)]

...to the same effect.

Upvotes: 4

Related Questions