矩阵 Python 每一行的总和数 [英] Sum numbers of each row of a matrix Python

查看:67
本文介绍了矩阵 Python 每一行的总和数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lista = [[1,2,3],[4,5,6],[7,8,9]]打印(列表)def filas(lista):资源=[]对于lista中的元素:x = sum(lista[elemento])res.append(x)打印(资源)

我需要对每一行的数字求和,然后将其打印为列表.我的问题似乎是我尝试对子列表求和,而不是对每一行的数字求和.

解决方案

您遇到的问题是您已经在迭代元素,因此没有必要将其用作索引:

 x = sum(elemento)

它通常被认为是不好的形式,但要迭代您将使用的索引:

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

但是,在不引入任何其他模块的情况下,您可以使用 map() 或简单的列表推导式:

<预><代码>>>>res = list(map(sum, lista)) # Py2 中不需要`list()`>>>打印(资源)[6, 15, 24]

<预><代码>>>>res = [sum(e) for e in lista]>>>打印(资源)[6, 15, 24]

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.

解决方案

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]

这篇关于矩阵 Python 每一行的总和数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆