繁体   English   中英

在Python中将元组元素追加到元组的元组

[英]Append tuple elements to a tuple of tuples in Python

如果我有一个元组,例如x = (1, 2, 3)并且我想将其每个元素附加到元组的每个元组的每个元组的前面,例如y = (('a', 'b'), ('c', 'd'), ('e', 'f'))因此最终结果为z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')) ,最简单的方法是什么?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM