我有这个代码,它会提示用户输入一个包含整数矩阵的 .mtx 文件(例如 Mydata.mtx
)。程序会取这个矩阵,转置它,然后用转置矩阵创建一个新文件。
该文件是一个简单的 .mtx 文件。
原始文件(Mydata.mtx):
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15 #separated by a tap "\t" to be a matrix
这是代码:def readMatrix(filename):
listOfLists = []
file = open(filename)
for i in file:
listOfLists.append(i.split())
return listOfLists
def transpose(M):
mtranspose = [list(i) for i in zip(*M)]
return mtranspose
def writeMatrix(M, filename):
for i in M:
convertListToStr = str(i)
newFile = open("T_" + filename, "w")
newFile.write(convertListToStr)
newFile.close()
callFile = input("Enter the file name: ")
toReadFile = readMatrix(callFile)
toTranspose = transpose(toReadFile)
ToWriteMatrix = writeMatrix(toTranspose, callFile)
代码起作用,因为它转置矩阵并创建一个新文件。所以问题出在第三个函数 writeMatrix
在 for i in M
因为它不会打印出整个矩阵,而只是以列表形式打印出最后一行。我需要它的字符串形式。我的输出(在新文件中):
T_Mydata.mtx
['5', '10', '15']
所需的输出:1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
有人可以帮忙吗?
最佳答案
您需要在循环时写入矩阵中的每一行,您还需要连接行中的每个元素,而不是将整行转换为字符串
def writeMatrix(M, filename):
with open("T_" + filename, "w") as f:
for row in M:
f.write(" ".join(row) + "\n")
关于python - 将列表转换为 str 并写入新的 .mtx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67155246/