[英]Performing a row sum and column sum on a list of lists in python
I want to calculate the row sum and column sum of a matrix in python;我想在python中计算矩阵的行和和列和; however, because of infosec requirements I cannot use any external libraries.
但是,由于信息安全要求,我不能使用任何外部库。 So to create a matrix, I've used a list of lists, as follows:
因此,为了创建一个矩阵,我使用了一个列表列表,如下所示:
matrix = [[0 for x in range(5)] for y in range(5)]
for pos in range(5):
matrix[pos][pos]=1
matrix[2][2]= 0
Now what I want to do is perform a rowsum and a column sum of the matrix.现在我想做的是执行矩阵的行和和列和。 I know how to do a row sum, that's quite easy:
我知道如何进行行总和,这很容易:
sum(matrix[0])
but what if I wanted to do a column sum?但是如果我想做一个列总和怎么办? Is there a more elegant and pythonic way to accomplish that beyond brute-forcing it with a for loop, a la
有没有更优雅和 Pythonic 的方式来完成它,而不是用 for 循环强制它,a la
sumval = 0
for pos in range(len(matrix[0])):
sumval = matrix[pos][0] + sumval
which would work, but it isn't pythonic at all.这会起作用,但它根本不是pythonic。
Can anyone help me out?谁能帮我吗?
colsum = sum(row[0] for row in matrix)
As a note for others who look at this question though, this really is a task best left to numpy
. 不过,对于其他关注此问题的人来说,这确实是
numpy
最好的任务。 OP is not allowed external libraries however. 但是不允许使用OP外部库。
I'd suggest: 我建议:
s = 0
for row in matrix:
s += row[0]
which is the same as you are doing but a bit more readable. 与您的操作相同,但可读性更高。
Using something like: 使用类似:
s = sum([row[0] for row in matrix])
is also readable, but slower because you need to do one pass to collect the row[0] elements, and a second to sum. 也是可读的,但速度较慢,因为您需要执行一次传递来收集row [0]元素,然后进行第二次求和。
您可以使用:
sum([matrix[i][0] for i in range(len(matrix[0]))])
I can suggest, define a method to calculate the sum by rows, which returns the list of sums: 我可以建议定义一个按行计算总和的方法,该方法返回总和列表:
def sum_rows(matrix):
return [sum(row) for row in matrix]
Then define a method that calls sum_rows(matrix) on the transposed matrix: 然后定义一个在转置矩阵上调用sum_rows(matrix)的方法:
def sum_cols(matrix):
return sum_rows(map(list, zip(*matrix)))
For transposing a matrix: Transpose list of lists 对于转置矩阵: 转置列表列表
Alternative to transpose: 转置的替代方法:
def sum_cols_alt(matrix):
return [ sum(row[i] for row in matrix) for i, _ in enumerate(matrix) ]
One way to do this is to use the map function:一种方法是使用 map 函数:
for sum_row, sum_col in zip(map(sum, matrix), map(sum, zip(*matrix))):
print(sum_row, sum_col)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.