簡體   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