sum of first value in nested list

2020-03-22 07:21发布

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]])

We find the error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

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

6条回答
迷人小祖宗
2楼-- · 2020-03-22 07:37

OR you can use zip :

>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> sum(zip(*l)[0])
12
查看更多
干净又极端
3楼-- · 2020-03-22 07:38

You can create a function to find sum of nested lists:

def nested_sum(par):
    total = 0 
    for k in par:
        if isinstance(k, list):  # checks if `k` is a list
            total += nested_sum(k)
        else:
            total += k
    return total

@Kasara and @Bhargav also have some neat answers , check them out!

查看更多
贪生不怕死
4楼-- · 2020-03-22 07:41

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

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

Or you can call the __next__ method as list is an iterable (If Py3)

>>> sum(zip(*a).__next__())
12
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-03-22 07:44

For python beginners:

By normal for loop and use try and except to handle exception when bested list is empty.

>>> l = [[1,2,3],[4,5,6],[7,8,9], []]
>>> result = 0
>>> for i in l:
...     try:result += i[0]
...     except IndexError:pass
... 
>>> result
12
>>> 
查看更多
SAY GOODBYE
6楼-- · 2020-03-22 07:57

Something like this is easy with numpy:

In [16]: import numpy as np

In [17]: a = [[1,2,3],[4,5,6],[7,8,9]]

In [18]: my_array = np.array(a)

In [19]: my_array[:,0].sum()
Out[19]: 12
查看更多
▲ chillily
7楼-- · 2020-03-22 07:59
>>> sum(map(lambda x:x[0],[[1,2,3],[4,5,6],[7,8,9]]))
12
查看更多
登录 后发表回答