gpt4 book ai didi

python - 将列表的内容写入文本文件

转载 作者:行者123 更新时间:2023-12-01 05:23:18 25 4
gpt4 key购买 nike

我想将列表的内容写入文本文件。我目前的做法如下:

for k in li:
outp.write(str(k))
out.write('\n')

但是,这需要很长时间才能运行(我有数千万行)

有没有更快的方法?

示例行

这些列表来自稀疏矩阵,因此有很多零。非空元素只是一个

例如这样的列表:[0 0 0 0 0 0 0 1 0 0 1 1 1 0 0]

数字之间用制表符分隔

最佳答案

我想知道存储 1 的坐标是否会产生所需的加速,正如您提到的这是一个稀疏矩阵。考虑以下因素:

写入文件:

def writeMatrix(matrix):
ones = [[i for i,num in row if num==1] for row in matrix]
with open('path/to/file', 'w') as outfile:
for row in ones:
outfile.write(' '.join(str(i) for i in row))
outfile.write('\n')

从文件中读取:

def readMatrix(infilepath, width):
answer = []
with open(infilepath) as infile:
for line in infile:
row = [None]*width
for i in set(int(i) for i in line.split()):
row[i] = 1
answer.append(row)
return answer

关于python - 将列表的内容写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903627/

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