simplify printing of a list
lbates at swamisoft.com
Fri Jun 4 01:12:20 CEST 2004
print ''.join(["%6d" % j for j in [0,1,2]])
print reduce(lambda x,y: x+"%6d" % y, [0,1,2], '')
t=[sys.stdout.write("%6d" % j for j in [0,1,2]]
(note: the t assignment is so the list comprehension
results don't print)
all work and are pythonic in nature. I didn't
test, but I'll be the last one is the most
<beliavsky at aol.com> wrote in message
news:3064b51d.0406031408.1b676379 at posting.google.com...
> To print a list with a specified format one can write (for example)
> for j in [0,1,2]:
> print "%6d"%j,
> The code
> print "%6d"%[0,1,2]
> currently produces a syntax error, but it would be convenient if it
> had the same meaning as the loop above.
> One can write a function to print a list, for example
> def print_list(x,fmt_x="%6d"):
> """ print a list on one line """
> for y in x: print fmt_x % y,
> but it gets messy to print several lists on the same line.
> In Fortran 90/95 one can write
> print "(100i6)",(/0,1,2/)
> where the format (100i6) means that UP TO 100 integers are printed
> using 6 columns. An alternative suggestion I have for Python is to
> print "100%6d"%[0,1,2]
> with the same meaning.
> I realize that what I am asking for is just a convenience, but it is
> one that I could use in almost every program I write.
More information about the Python-list