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?

有帮助吗?

解决方案

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)]

其他提示

one without using for loop,

zip(*(zip(*a)+ [b]))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top