我正在尝试创建一个函数,该函数将查找 2D 列表的一列的元素总和,但只有一个特定列。我可以找到很多关于如何找到列表中每一列的总和的例子,但不是一个只给我一个特定列的例子。并且列表必须来自不同的功能。
def sumColumn(matrix, columnIndex):
(No idea what on earth to put here...)
return total
我正在尝试创建一个函数,该函数将查找 2D 列表的一列的元素总和,但只有一个特定列。我可以找到很多关于如何找到列表中每一列的总和的例子,但不是一个只给我一个特定列的例子。并且列表必须来自不同的功能。
def sumColumn(matrix, columnIndex):
(No idea what on earth to put here...)
return total
对于繁重的矩阵工作,建议使用numpy:
>>> import numpy as np
>>> matrix = [[0, 2, 0],
[0, 1, 0]]
>>> columnIndex = 1 # 1 means the second(middle) column
>>> np.array(matrix)[:, columnIndex].sum()
3
在纯 Python 中:
sum(row[columnIndex] for row in matrix)
单线:
sum_column = lambda l, i: sum(x[i] for x in l)
更具可读性,几乎是英文:
def sum_column(matrix, index):
return sum(line[index] for line in matrix)