Jsg91
Jsg91

Reputation: 465

Outputting lists as columns

I have 3 large lists I want outputted as columns, [0][0][0] and then down. My current written code (that worked for smaller lists) is this:

f=open("Clustered_energies.txt", "w")
for i in range(0, len(frame_position)):
print >> f, frame_position[i],energy[i],cell_volume[i]
f.close()

That gives me a list index out of range error. I'm guessing I need to use a list comprehension and I tried this:

print [(i,e,c) for i in frame_position for e in energy for c in cell_volume]

But the output from that repeats a value from each list over and over, is a list comprehension the way to go? Or can my original code be fixed?

Upvotes: 1

Views: 105

Answers (2)

halex
halex

Reputation: 16403

My first idea was using zip but it stops at the shortest list and so I would use izip_longest (it is called zip_longest in Python3 for future reference):

import itertools
for i, e, c in itertools.izip_longest(frame_position, energy, cell_volume, fillvalue=" "):
    print i, e, c

Upvotes: 1

jmdana
jmdana

Reputation: 439

Something like this?

[[x,y,z] for x,y,z in zip(frame_position,energy,cell_volume)]

Upvotes: 3

Related Questions