简体   繁体   English

在这种情况下python中的sum函数如何工作(加和一个列表的元组)

[英]how sum function in python works with this case (adding up tuples of a list)

I am trying to use sum() function in my code, but there is an error, which i did not understand why. 我正在尝试在代码中使用sum()函数,但是有一个错误,我不明白为什么。 How can i solve this problem 我怎么解决这个问题

my code should add up tuples of a list so the output should be like this 我的代码应该将一个列表的元组加起来,所以输出应该像这样

the input: 输入:

a = [(1, 2, 3), (4, 5, 6)] a = [(1、2、3),(4、5、6)]

the output: 输出:

(5, 7, 9) (5、7、9)

this is my code 这是我的代码

a = [(1, 3, 5), (2, 3, 5), (3, 3, 5), (4, 3, 5)]
a = iter(a)
b = next(a)
for x in a:
    b = sum(b, x)
print(b)

The error is: 错误是:

TypeError: can only concatenate tuple (not "int") to tuple

This can be done using the zip builtin function: 这可以使用zip内置函数来完成:

[sum(x) for x in zip(*a)]

Full console session: 完整的控制台会话:

>>> a = [(1, 2, 3), (4, 5, 6)]
>>> list(zip(*a))  # "Make an iterator that aggregates elements from each of the iterables"
[(1, 4), (2, 5), (3, 6)]
>>> [sum(x) for x in zip(*a)]
[5, 7, 9]
>>>

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

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