I have five lists I need to make into a text file each in their own column. So far I have
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))
I want it to write a text file that goes
Velocity Angle Impact y Distance
Velocity Angle Impact y Distance
Velocity Angle Impact y Distance
and so on
I can not figure out how to do this.
Assuming you have all the five lists of the same length,
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]))
You can use *args to unpack the columns into 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')
Which outputs
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.