gpt4 book ai didi

python - 每 4 个选项卡写一个新行文本文件 python

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

如果我有以下使用制表符分隔打印的数据

print str(z).translate(None,"([]){},\"'").replace(' ','\t')

0.016611783537845426 0.5728972505882961 0.1723653381777387 0.44730982873820446 10 11 10 0.016611783537845426 0.5728972505882961 0.2526385373738682 0.03281263933004819 10 12 10 0.016611783537845426 0.5728972505882961 0.509414248773428

我如何写入一个新的 txt 文件,但每说 4 个选项卡就开始换行。所以得到 4 列。

已经尝试了\n 的许多变体,但我很烂。

例如:

 open("file.txt", "w").write('\n'.join(str(z).translate(None,"([]){},\"'").replace(' ','\t')))

为每个字符返回一个换行符。

最佳答案

您可以使用 itertools documentation 中的grouper 食谱:

import itertools as it
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return it.izip_longest(fillvalue=fillvalue, *args)

然后您可以将输出生成为:

values = str(z).translate(None,"([]){},\"'").split()
output = '\n'.join('\t'.join(x for x in g if x) for g in grouper(4, values))

或者如果你想把它写入一个文件,使用f.writelines:

f.writelines('\t'.join(x for x in g if x) + '\n' for g in grouper(4, values))

关于python - 每 4 个选项卡写一个新行文本文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10078086/

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