問題描述
在傳統的python中,sum
函數給出一個list
的總和:
In traditional python, the sum
function gives the sum of a list
:
sum([0,1,2,3,4])=10
另一方面,如果你有一個嵌套列表怎么辦:
On the other hand, what if you have a nested list as so:
sum([[1,2,3],[4,5,6],[7,8,9]])
我們發現錯誤:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
除此之外,我們如何在嵌套列表中找到第一個值(索引 0)的 sum
?如:
In addition to this, how could we find the sum
of the first values (index 0) in a nested list? Such as:
something([[1,2,3],[4,5,6],[7,8,9]])=12
推薦答案
要獲得所有第一個元素的總和,您需要有一個生成器表達式
To get the sum of all the first elements you need to have a generator expression
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> sum(i[0] for i in a)
12
您得到 unsupported operand type(s) for +: 'int' and 'list'
因為您嘗試添加三個列表,這不是所需的行為.
You are getting unsupported operand type(s) for +: 'int' and 'list'
because you are trying to add the three lists which is not the desired behavior.
如果您想要一個第一個元素的列表,然后找到它們的總和,您可以嘗試使用列表推導
If you want a list of first elements and then find their sum, you can try a list comprehension instead
>>> l = [i[0] for i in a]
>>> l
[1, 4, 7]
>>> sum(l)
12
或者您可以調用 __next__
方法,因為列表是可迭代的(如果 Py3)
Or you can call the __next__
method as list is an iterable (If Py3)
>>> sum(zip(*a).__next__())
12
這篇關于嵌套列表中第一個值的總和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!