我可以将零列中的项目加总。但是,在哪里更改代码以将矩阵中的第2列,第3列或第4列求和?我很容易陷入困境。
def main(): matrix = [] for i in range(2): s = input("Enter a 4-by-4 matrix row " + str(i) + ": ") items = s.split() # Extracts items from the string list = [ eval(x) for x in items ] # Convert items to numbers matrix.append(list) print("Sum of the elements in column 0 is", sumColumn(matrix)) def sumColumn(m): for column in range(len(m[0])): total = 0 for row in range(len(m)): total += m[row][column] return total main()
这是更改您的代码以返回指定的任何列的总和:
def sumColumn(m, column): total = 0 for row in range(len(m)): total += m[row][column] return total column = 1 print("Sum of the elements in column", column, "is", sumColumn(matrix, column))