gpt4 book ai didi

Python:将大数组写入文本文件

转载 作者:行者123 更新时间:2023-11-30 23:42:11 28 4
gpt4 key购买 nike

我是Python新手,我有一个解决方案,但它看起来又慢又傻,所以我想知道是否有更好的方法?

假设我有一个这样定义的矩阵:

mat = [['hello']*4 for x in xrange(3)]

我正在使用此函数将其写入文件:

def writeMat(mat, outfile):
with open(outfile, "w") as f:
for item in mat:
f.writelines(str(item).replace('[','').replace(',','').replace('\'','').replace(']','\n'))

writeMat(mat, "temp.txt")

它给出了一个如下所示的文本文件:

hello hello hello hello
hello hello hello hello
hello hello hello hello

我正在处理的文件非常大。 numpy 中的 savetxt 函数会很棒,但我不想将其存储为 numpy 数组,因为虽然矩阵的大部分由单个字符元素组成,但前几列会很多字符长度,在我看来(如果我错了,请纠正我)这意味着整个矩阵将使用比所需更多的内存,因为矩阵中的每个元素都将是最大元素的大小。

最佳答案

如果我正确理解你的问题,你可以这样做:

f.writelines(' '.join(row) + '\n' for row in mat)

f.write('\n'.join(' '.join(row) for row in mat))

第一个的优点是它是一个生成器表达式,仅生成当前行的串联字符串副本

如果你的矩阵条目不是字符串,你可以这样做:

f.writelines(' '.join(str(elem) for elem in row) + '\n' for row in mat)

编辑

看来,file.writelines() 方法在将整个生成器表达式写入文件之前对其进行计算。因此,以下内容可以最大限度地减少您的内存消耗:

for row in mat:
f.write(' '.join(row) + '\n')

关于Python:将大数组写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11589583/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com