Domanda

Assume I have a list of two-element tuples and a list of (not tuple) literals e.g. integer:

a = [('x', 'a'), ('y', 'b'), ('z', 'c')]
b = [1, 2 ,3]

And I want to make a list of three-element tuples so I coded like below:

zipped = zip((t[0] for t in a), (t[1] for t in a), b)
assert zipped == [('x', 'a', 1), ('y', 'b', 2), ('z', 'c', 3)]

My current code works pretty well but I want to know that is there any more efficient and elegant recipe however my code have to iterate and unpack every tuples twice. Can anyone please advise?

È stato utile?

Soluzione

Using list comprehension, tuple unpacking:

>>> a = [('x', 'a'), ('y', 'b'), ('z', 'c')]
>>> b = [1, 2 ,3]
>>> [(x,y,z) for (x,y), z in zip(a, b)]
[('x', 'a', 1), ('y', 'b', 2), ('z', 'c', 3)]

>>> a = [('x', 'a'), ('y', 'b'), ('z', 'c')]
>>> b = [1, 2 ,3]
>>> [x + (y,) for x, y in zip(a, b)]
[('x', 'a', 1), ('y', 'b', 2), ('z', 'c', 3)]

Altri suggerimenti

one without using for loop,

zip(*(zip(*a)+ [b]))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top