2016-05-22 28 views
2

Wenn ich ein Tupel habe, z. x = (1, 2, 3) und ich möchte jedes seiner Elemente an die Vorderseite jedes Tupels eines Tupel-Tupels, z. y = (('a', 'b'), ('c', 'd'), ('e', 'f')), so dass das Endergebnis ist z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')), was ist der einfachste Weg?Tupel-Elemente an ein Tuple-Tupel in Python anhängen

Mein erster Gedanke war zip(x,y), aber das produziert ((1, ('a', 'b')), (2, ('c', 'd')), (3, ('e', 'f'))).

Antwort

2

Verwenden zip und glätten das Ergebnis:

>>> x = (1, 2, 3) 
>>> y = (('a', 'b'), ('c', 'd'), ('e', 'f')) 
>>> tuple((a, b, c) for a, (b, c) in zip(x,y)) 
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')) 

Oder, wenn Sie Python verwenden 3.5, tun es in der Art:

>>> tuple((head, *tail) for head, tail in zip(x,y)) 
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')) 
2
tuple((num,) + other for num, other in zip(x, y)) 

Oder

from itertools import chain 

tuple(tuple(chain([num], other)) for num, other in zip(x, y)) 
+0

I sehe keinen Vorteil für die 'chain' Version. –

+0

@AlexHall es ist nur eine weitere Option für den Rekord. –

Verwandte Themen