本文介紹了python中的求和矩陣列的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我可以對第零列中的項目求和.但是我在哪里更改代碼以求和矩陣中的第 2 列、第 3 列或第 4 列?我很容易被難住.
I can sum the items in column zero fine. But where do I change the code to sum column 2, or 3, or 4 in the matrix? I'm easily stumped.
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()
推薦答案
您的代碼更改為返回您指定的任何列的總和:
Here is your code changed to return the sum of whatever column you specify:
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))
這篇關于python中的求和矩陣列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!