2016-05-22 48 views
2

如果我有一个元组,例如x = (1, 2, 3),我想将它的每个元素追加到元组元组的元组的每个元组的前面,例如y = (('a', 'b'), ('c', 'd'), ('e', 'f'))这样最终的结果是z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')),最简单的方法是什么?将元组追加到Python元组的元组中

我的第一个想法是zip(x,y),但这产生((1, ('a', 'b')), (2, ('c', 'd')), (3, ('e', 'f')))

回答

2

使用zip和扁平化的结果:

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

或者,如果你正在使用Python 3.5,做到这一点的风格:

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

或者

from itertools import chain 

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

我没有看到'链'版本的任何好处。 –

+0

@AlexHall它只是记录的另一种选择。 –