質問

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