我可以对零列中的项目进行求和。但是我应该在哪里更改代码以对矩阵中的第 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()
numpy 可以很容易地为你做到这一点:
def sumColumn(matrix):
return numpy.sum(matrix, axis=1) # axis=1 says "get the sum along the columns"
当然,如果您想手动完成,我将如何修复您的代码:
def sumColumn(m):
answer = []
for column in range(len(m[0])):
t = 0
for row in m:
t += row[column]
answer.append(t)
return answer
不过,还有一种更简单的方法,使用 zip:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)