Sum numbers of each row of a matrix Python

2019-07-31 01:07发布

lista = [[1,2,3],[4,5,6],[7,8,9]]

print(lista)

def filas(lista):

    res=[]
    for elemento in lista:
        x = sum(lista[elemento])
        res.append(x)
    print(res)

I need to sum the numbers of each row, and then print it as a list. It seems the problem I have is that I try to sum the sublists, instead of the numbers of each row.

标签: python sum
3条回答
来,给爷笑一个
2楼-- · 2019-07-31 01:46

Is this what you want to do?

def filas(lista):
    res=[]
    for elemento in lista:
        x = sum(elemento) # <- change this line.
        res.append(x)
    print(res)
查看更多
Fickle 薄情
3楼-- · 2019-07-31 01:52

The issue you are having, is that you are already iterating over the elements so it is unnecessary to use it as an index:

    x = sum(elemento)

It is generally considered bad form but to iterate over indexes you would use:

for i in range(len(lista)):
    x = sum(lista[i])

However, without introducing any other modules, you can use map() or a simple list comprehension:

>>> res = list(map(sum, lista))   # You don't need `list()` in Py2
>>> print(res)
[6, 15, 24]

Or

>>> res = [sum(e) for e in lista]
>>> print(res)
[6, 15, 24]
查看更多
一夜七次
4楼-- · 2019-07-31 01:55

Do you want like this?

lista = [[1,2,3],[4,5,6],[7,8,9]]

print(lista)

def filas(lista):
    summed_list = [sum(i) for i in lista]
    print(summed_list)
filas(lista)
查看更多
登录 后发表回答