Sum Numbers Of Each Row Of A Matrix Python
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 n
Solution 1:
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 inrange(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]
Solution 2:
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)
Solution 3:
You can do this easly, with dot product. This is much faster than any loop.
lista = np.float32([[1,2,3],[4,5,6],[7,8,9]])
vet_one = np.ones(len(lista))
vet_sum = lista.dot(vet_one)
Solution 4:
Is this what you want to do?
deffilas(lista):
res=[]
for elemento in lista:
x = sum(elemento) # <- change this line.
res.append(x)
print(res)
Post a Comment for "Sum Numbers Of Each Row Of A Matrix Python"