如何在元组中单独添加元素? [英] How to add elements individually in tuple?

查看:1271
本文介绍了如何在元组中单独添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在元组中单独添加元素?

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)

推荐答案

您可以在此处使用zipsum:

示例:

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

      这篇关于如何在元组中单独添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆