[英]How do I write multiple lists into their own column in a text file?
我有五个列表需要制作成一个文本文件,每个列表都在它们自己的列中。 到目前为止我有
with open("PR.txt","w") as f:
PR = [[Velocity], [Angle], [Impact], [y], [Distance]]
for (x) in zip(PR):
f.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(*x))
我希望它写一个文本文件
Velocity Angle Impact y Distance
Velocity Angle Impact y Distance
Velocity Angle Impact y Distance
等等
我不知道如何做到这一点。
假设您拥有相同长度的所有五个列表,
with open("PR.txt","w") as f:
f.write("Velocity\tAngle\tImpact\ty\tDistance")
for i in range(0, len(Velocity)):
# Velocity here is the list
f.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(Velocity[i],Angle[i], Impact[i], y[i], Distance[i]))
您可以使用 *args 将列解压缩为zip
:
# test input
pr = [['v 0', 'v 1', 'v 2', 'v 3', 'v 4'], ['10', '11', '12', '13', '14'], ['0', '1', '2', '3', '4'], ['y0', 'y1', 'y2', 'y3', 'y4'], ['dist 0', 'dist 1', 'dist 2', 'dist 3', 'dist 4']]
with open('file.txt', 'w') as fh:
cols = ['Velocity', 'Angle', 'Impact', 'y', 'Distance']
fh.write('\t'.join(cols) + '\n')
# here is where you unpack everything
for row in zip(*pr):
fh.write('\t'.join(row) + '\n')
哪些输出
Velocity Angle Impact y Distance
v 0 10 0 y0 dist 0
v 1 11 1 y1 dist 1
v 2 12 2 y2 dist 2
v 3 13 3 y3 dist 3
v 4 14 4 y4 dist 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.