将数组写入文本文件,每行中具有最大数量的元素



我是python的初学者,我试图解决我的问题很多小时,但没有成功。

我的问题:我有一个包含 12 个元素的数组A,我想将A写入文本文件。

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]

文本文件的最大列数为 8。所以我的新文件应该看起来像这样:

*Header...
1, 2, 3, 4, 5, 6, 101, 102,
103, 104, 105, 106

我找不到可以指定最大列数并将分隔符设置为,的解决方案。

你能帮我解决这个问题吗?

这是一个简单易读的解决方案,带有注释,可以将列表解析为文本文件。如果您计划使用更大的数据集或删除末尾的分隔符,我建议您考虑使用切片或缓存算法的某些变体来提高性能。

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
with open("fout.txt", "w") as f:
# set width in a variable
width = 8
# Loop through each element in the list k = key, i = element (numeric in this case)
for k, i in enumerate(A):
# check for every 8th entry using mod on index of list to print the new line character at the end
if (k+1) % width == 0:
f.write(str(i)+",n")
# otherwise just print the next element in the list followed by a comma (change to variable for a different delimiter)
else:
f.write(str(i)+", ")

chunks 函数将数组拆分为大小为 n 的块(它是一个生成器函数(;在这里,我们决定 n 根据 o/p 为 8

现在来到print函数,它是一个函数,它将您在第一眼中所说的要打印的任何内容输出到控制台窗口。但是,如果您从文档中查看它的签名,您会发现它也可能需要很少的参数。

print的函数签名看起来像print(*objects, sep=' ', end='n', file=sys.stdout, flush=False);

我们专注于filearg,因为默认情况下它是sys.stdout的,即将所有内容写入控制台;所以我们能做的就是用一个带有 write(string( 方法的对象来更改它;

def chunks(lst, n):
# Yield successive n-sized chunks from the list..
for i in range(0, len(lst), n):
yield lst[i:i + n]
with open('my_file.txt', 'w') as fp: 
for my_chunk in chunks(l, n=8): # save them
print(my_chunk, file=fp)

如何itertools.zip_longestiter对列表进行分块:

from itertools import zip_longest
A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
a_iter = iter(A)
with open('fn.txt') as f:
for n in zip_longest(*[a_iter]*8):
f.write(', '.join(map(str, filter(None.__ne__, n))) + 'n')

每次都可以从列表中切片 n 个元素(根据所需的列数(,并将它们写入输出文件。

例如:

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
A = list(map(str, A))
cols = 8
start_index = 0
with open("output.txt", "w") as f:
while start_index <= len(A) - 1:
f.write(",".join(A[start_index:start_index + cols])+"n")
start_index += cols

以下是您可以执行的操作:

A = [1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 106]
with open("file.txt","w") as f:
while len(A) > 8:
f.write(', '.join([str(n) for n in A[:8]])+'n')
A = A[8:]
f.write(', '.join([str(n) for n in A]))

最新更新