简体   繁体   English

如何添加两个元组(或列表)的内容?

[英]How to add the content of two tuples (or lists)?

I already had this problem multiple times, that I couldn't find a good solution to add the content of two tuples together. 我已经多次遇到过这个问题,我找不到一个好的解决方案来将两个元组的内容一起添加。 Something that does : 做的事:

a = (1, 2)
b = (3, 4)
c = (a[0]+b[0], a[1]+b[1])

I think I saw a syntax to do just that once, but I can't remember how to do it. 我想我曾经看到过这样做的语法,但我不记得该怎么做了。

This one also works: 这个也有效:

>>> a = (1,2)
>>> b = (3,4)
>>> c = map(sum, zip(a,b))
>>> c
[4, 6]

It should work with any number of lists containing any number of numbers. 它应该适用于任意数量的包含任意数量的数字的列表。

One liner: 一个班轮:

map(lambda x, y: x+ y, a, b)

I believe this is the most efficient way. 我相信这是最有效的方式。 You can also import operator.add to avoid the lambda function. 您还可以导入operator.add以避免lambda函数。 For me I rather prefer cleaner global namespace. 对我来说,我更喜欢更清洁的全局命名空

With generator comprehension: 有了生成器理解力:

a = (1, 2)
b = (3, 4)
result = [x + y for x, y in zip(a, b)]

[4, 6] [4,6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM