如何在元组中单独添加元素?
问题描述:
如何在元组中单独添加元素?
How to add elements individually within the tuple?
例如,我需要(0,1)
+ (2,3)
中的(2, 4)
,我一直在这样做,但是有没有更多的pythonic/更少冗长的方法来做到这一点?
For example, i need (2, 4)
from (0,1)
+ (2,3)
, I've been doing it as such but is there a more pythonic / less verbose way to do the same?
>>> x = (0,1)
>>> y = (2,3)
>>> x + y
(0, 1, 2, 3)
>>> tuple(i+j for i,j in zip(x,y))
(2, 4)
答
您可以在此处使用zip
和sum
:
示例:
>>> x = (0, 1)
>>> y = (2, 3)
>>> tuple(map(sum, zip(x, y)))
(2, 4)
-
zip
让我们成对地组合两个可迭代对象或列表的元素. -
sum
让我们对这些对求和 -
map
让我们每对应用sum
函数. - 最终,我们将结果列表(在Python 3.x中为或可迭代的)转换回
tuple
,因为这似乎是您想要的. -
zip
lets us combine elements of two iterables or lists in pairs. -
sum
lets us sum the pairs -
map
lets us apply thesum
function per pair. -
finally we convert the resulting list (or iterable in Python 3.x) back into a
tuple
since that's what you seem to have wanted.
上面的例子基本上以"
(0 + 2, 1 + 3)