python - 将列表转换为 str 并写入新的 .mtx 文件

标签 python python-3.x function file

我有这个代码,它会提示用户输入一个包含整数矩阵的 .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)
代码起作用,因为它转置矩阵并创建一个新文件。所以问题出在第三个函数 writeMatrixfor 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/

相关文章:

python-3.x - 将鼠标悬停在wxpython选项卡上时发生错误

javascript - 在悬停时使用 jQuery .animate 显示新的 div

python - 循环搜索字符串直到找到字符串 python

python - 如何将 NLTK block 输出到文件?

python - python 在 float 前插入逗号

python - 仅当添加和减去相同的值时,使用 pyplot 绘制常量函数才有效。为什么?

javascript - 跨浏览器 Javascript 函数作用域问题

python - 如何绘制 numpy 数组与行数的关系图

python - 在Python中,我放入了print(),但仍然收到语法错误

Python3.3 : Square-root optimization