change line with columns when print

MRAB google at mrabarnett.plus.com
Wed Oct 1 11:30:15 EDT 2008


On Oct 1, 1:13 pm, "D'Arcy J.M. Cain" <da... at druid.net> wrote:
> On Wed, 1 Oct 2008 04:43:34 -0700 (PDT)
>
> sandric ionut <sandricio... at yahoo.com> wrote:
>
> > Hello:
> > I have a text file that looks like:
> > 0 23
> > 1 342
> > 3 31
> > and I want to read the file and print it out like:
> > 0 1 3
> > 23 342 31
>
> > How can I do this?
>
> Probably tons of ways.  Here's one with no input checking.
>
> L = [x.strip().split() for x in open("infile") if x]
> for i in range(2):
>   print ' '.join([x[i] for x in L])
>
Here's another way:

rows = [line.strip().split() for line in open("infile") if line]
columns = zip(*rows)
for col in columns:
    print " ".join(col)




More information about the Python-list mailing list