我知道如何做這樣的行的總和:row = [sum(row) for row in Matrix]
,但如何找到一個python矩陣中的列的總和?找到一個python矩陣中的列的總和?
如果我有這樣的矩陣:
Matrix =[[0, 2, 2],
[0, 2, 2],
[0, 0, 2]]
應該讓3個值,它們分別是:0
,4
和6
。
我知道如何做這樣的行的總和:row = [sum(row) for row in Matrix]
,但如何找到一個python矩陣中的列的總和?找到一個python矩陣中的列的總和?
如果我有這樣的矩陣:
Matrix =[[0, 2, 2],
[0, 2, 2],
[0, 0, 2]]
應該讓3個值,它們分別是:0
,4
和6
。
Look here同樣的問題,很好的示例代碼。看看
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))
你可以看看,每次添加一個索引,所以你看下一列
,或者您可以使用壓縮:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
或here simplere方式:
sum(m[:,i]) for i in range(4)
比一些其他答案更爲pythonic方式:
[sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]
位在緩存性能方面效率非常低。所以儘量避免它,或者如果您需要多次在同一個矩陣上執行此操作,請先轉置矩陣。
從here
試試這個,它由指定的列求和矩陣:
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))
import numpy as np
Matrix =[[0, 2, 2],
[0, 2, 2],
[0, 0, 2]]
np.asarray(Matrix).sum(axis=0)
Out[66]: array([0, 4, 6])
這是相當自我解釋,但別人問到註釋代碼。
代碼首先將矩陣轉換爲一個numpy數組,然後對數組進行求和,這就是這個問題的含義。
請編輯您的答案,包括一些解釋。僅有代碼的答案對未來SO讀者的教育很少。您的回答是在低質量的審覈隊列中。 – mickmackusa
看看[這裏](http://stackoverflow.com/questions/23145684/sum-matrix-columns-in-python)同樣的問題,很好的示例代碼 – BlooB
@dirty_feri在另一篇文章中,它展示瞭如何找到列指定的行是否有自動查找所有行的總和的方法? –
[zip()](https://docs.python.org/3/library/functions.html#zip)將轉置您的列表清單。然後總結就像你在例子中顯示的那樣。 '''cols = [col(col)for col in zip(Matrix)]''' – wwii