如何将两个等长元组两两求和

发布于 2024-09-24 21:51:40 字数 69 浏览 0 评论 0原文

如何获得两个等长元组的两两求和?例如,如果我有 (0,-1,7) 和 (3,4,-7),我希望有 (3,3,0) 作为答案。

How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡淡的优雅 2024-10-01 21:51:40
tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))

如果您希望避免 maplambda 那么您可以这样做:

tuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))

编辑:正如答案之一指出的那样,您可以使用 sum 而不是显式分割 zip 返回的元组。因此,您可以重写上述代码示例,如下所示:

tuple(sum(t) for t in zip((0,-1,7), (3,4,-7)))

参考:zip地图sum

tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))

If you prefer to avoid map and lambda then you can do:

tuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))

EDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip. Therefore you can rewrite the above code sample as shown below:

tuple(sum(t) for t in zip((0,-1,7), (3,4,-7)))

Reference: zip, map, sum.

夜清冷一曲。 2024-10-01 21:51:40

使用 sum():

>>> tuple(sum(pair) for pair in zip((0,-1,7), (3,4,-7)))

>>> tuple(map(sum, zip((0,-1,7), (3,4,-7))))

Use sum():

>>> tuple(sum(pair) for pair in zip((0,-1,7), (3,4,-7)))

or

>>> tuple(map(sum, zip((0,-1,7), (3,4,-7))))
朦胧时间 2024-10-01 21:51:40
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
琴流音 2024-10-01 21:51:40

或者(如果您有非常大的元组或您计划对它们进行其他数学运算,则很好):

> import numpy as np
> t1 = (0, -1, 7)
> t2 = (3, 4, -7)
> at1 = np.array(t1)
> at2 = np.array(t2)
> tuple(at1 + at2)
(3, 3, 0)

缺点:需要更多的数据准备。在大多数情况下可能有点矫枉过正。

优点:操作非常明确且孤立。对于大元组来说可能非常快。

Alternatively (good if you have very big tuples or you plan to do other mathematical operations with them):

> import numpy as np
> t1 = (0, -1, 7)
> t2 = (3, 4, -7)
> at1 = np.array(t1)
> at2 = np.array(t2)
> tuple(at1 + at2)
(3, 3, 0)

Cons: more data preparation is needed. Could be overkill in most cases.

Pros: operations are very explicit and isolated. Probably very fast with big tuples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文