gpt4 book ai didi

python - 使用 write 函数编写格式良好的列表

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

我有两个带有数字的列表,我希望它们能很好地写出来,就像我从 print item1, item2 中得到的那样。有人可以帮忙吗?

outfile = open("tabal_t_y.dat", "w")
for item1, item2 in zip(t, y):
outfile.write()
outfile.close()

最佳答案

print

evaluates each expression in turn and writes the resulting object… If an object is not a string, it is first converted to a string using the rules for string conversions… A space is written before each object is (converted and) written…

但是,如果您在文档中进一步阅读:

print also has an extended form… sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object… the subsequent expressions are printed to this file object…

因此,您根本不必使用 outfile.write 执行此操作,您只需执行以下操作即可:

print >>outfile, item1, item2
<小时/>

但是如果您想使用 outfile.write,您可以通过两种不同的方式自行完成 print 所做的一切:

首先,您可以将输出转换为字符串,然后用空格将它们连接起来:

outfile.write(' '.join(map(str, (item1, item2))))

outfile.write(str(item1) + ' ' + str(item2))

def write_things(f, *things):
f.write(' '.join(map(str, things))))
write_things(outfile, item1, item2)

…或者任何你觉得舒服的东西。

或者您可以使用string formatting :

outfile.write('{} {}'.format(item1, item2))

关于python - 使用 write 函数编写格式良好的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26083809/

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