如何将两个等长元组两两求和
如何获得两个等长元组的两两求和?例如,如果我有 (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您希望避免
map
和lambda
那么您可以这样做:编辑:正如答案之一指出的那样,您可以使用 sum 而不是显式分割
zip
返回的元组。因此,您可以重写上述代码示例,如下所示:参考:
zip
、地图
、sum
。If you prefer to avoid
map
andlambda
then you can do: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:Reference:
zip
,map
,sum
.使用 sum():
或
Use sum():
or
或者(如果您有非常大的元组或您计划对它们进行其他数学运算,则很好):
缺点:需要更多的数据准备。在大多数情况下可能有点矫枉过正。
优点:操作非常明确且孤立。对于大元组来说可能非常快。
Alternatively (good if you have very big tuples or you plan to do other mathematical operations with them):
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.