Python从文件读取矩阵
这是我在上IT课时遇到的问题,我想计算每一行的总和。这是一个魔方程序。当我运行这个程序时,它提示“int对象不可迭代”。另外,老师希望函数的头部写成这样:def rowSum(matrix, rowNum),但我不明白为什么需要rowNum。这个函数应该能够计算任何大小矩阵每一行的总和。而且我不能使用numpy和enumerate,因为我们在课上还没有讲过这些。
矩阵的文本文件:
1 4
3 2
这是代码
def main():
filNam = "matrix1.txt"
matrix = (readMatrix(filNam))
print(eachNumPresent(matrix))
print(rowSum(matrix))
def readMatrix(filNam):
matrixFile = open(filNam, "r")
line = matrixFile.readline()
for line in matrixFile:
line = line.split()
return line
matrixFile.close()
def eachNumPresent(matrix):
if len(matrix) % 2 == 0:
return True
else:
print("Not enough numbers")
def rowSum(matrix, rowNum):
for line in matrix:
return(sum(int(line)))
main()
3 个回答
0
1. 你可以学习pandas这个工具。
2. 你的代码有错误,这里是我的代码。
def main():
filNam = "matrix1.txt"
rowNum, matrix = (readMatrix(filNam))
print(eachNumPresent(rowNum))
rowSum(matrix)
def readMatrix(filNam):
matrix_list = []
total_num = 0
with open(filNam, 'r') as matrixFile:
for line in matrixFile.readlines():
line = line.split()
line = [int(i) for i in line]
matrix_list.append(line)
total_num += len(line)
return total_num, matrix_list
def eachNumPresent(num):
if num % 2 == 0:
return True
else:
print("Not enough numbers")
def rowSum(matrix):
for row in matrix:
print sum(row)
main()
输出结果:
True
5
5
1
你没有正确地遍历序列,你用了“readline”而不是“readlines”。“readline”只读取了矩阵中的一行,而不是整个文件。你想做的是读取所有的行,并把这些行转换成列表,这样你就可以对它们使用sum()函数。注意,在分割之后,你需要确保把得到的字符串转换成整数。这样你就形成了一个列表的列表(格式是[[1,2],[3,4]]),然后你可以把行号(从零开始,但可以调整)传给rowSum方法(这就是老师给你这种格式的原因)。
看看更正后的例子中的不同之处(我把转换的步骤列出来了,虽然你可以把代码重构成更少的行):
def main():
filNam = "matrix1.txt"
matrix = (readMatrix(filNam))
print(eachNumPresent(matrix))
print(rowSum(matrix, 0))
def readMatrix(filNam):
with open(filNam, 'r') as matrixFile:
matrix = []
lines = matrixFile.readlines()
for line in lines:
items = line.split()
numbers = [int(item) for item in items]
print numbers
matrix.append(numbers)
return matrix
def eachNumPresent(matrix):
if len(matrix) % 2 == 0:
return True
else:
print("Not enough numbers")
def rowSum(matrix, rowNum):
for line in matrix:
return(sum(line))
main()
如果你需要任何解释,随时告诉我……希望这对你有帮助!
1
这样说吧,假设你想要第一行的数据,你就输入'0';如果你想要第二行的数据,就输入'1',依此类推……这个设置很容易修改。
def main():
fn = "matrix1.txt"
matrix = readMatrix(fn)
n = int(input("Enter row number: "))
rowSum(matrix, n)
def readMatrix(fn):
matrix = []
with open(fn) as f: # a with block will auto close your file after the statements within it
for line in f:
line = line.strip() # strip off any trailing whitespace(including '\n')
matrix.append(line.split())
return matrix
def rowSum(matrix, rowNum):
result = sum(int(i) for i in matrix[rowNum])
print("The sum of row {} = {}".format(rowNum, result))
main()
示例输出:
The sum of row 1 = 5
编辑:
要计算某一列的总和:
def main():
fn = "matrix1.txt"
matrix = readMatrix(fn)
n = int(input("Enter col number: "))
colSum(matrix, n)
def readMatrix(fn):
matrix = []
with open(fn) as f: # a with block will auto close your file after the statements within it
for line in f:
line = line.strip() # strip off any trailing whitespace(including '\n')
matrix.append(line.split())
return matrix
def colSum(matrix, colNum):
result = sum(int(row[colNum]) for row in matrix)
print("The sum of col {} = {}".format(colNum, result))
main()