simplify printing of a list
Eru
ripolles at LALALAaditel.org
Thu Jun 3 18:37:31 EDT 2004
beliavsky at aol.com escribio:
> To print a list with a specified format one can write (for example)
>
> for j in [0,1,2]:
> print "%6d"%j,
> print
>
> 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,
>
> print_list([0,1,2])
How about using:
def fmtlst(fmt,lst):
return fmt*len(lst) % tuple(lst)
print fmtlst("%3d",range(5)), fmtlst("%5.2f", [1.2, 3, 4.567])
This prints:
0 1 2 3 4 1.20 3.00 4.57
Maybe it gets your job done (though it's not the most efficient thing
one can do...)
>
> 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
> allow
>
> print "100%6d"%[0,1,2]
It looks a bit weird (unpythonic) to me, and we can use workarounds :)
>
> 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.
--
Daniel Ripolles ( Eru )
Make Source, Not War
for(0..pop){for($c=$_%2;$_>>=1;){$c=$_%2 .$c}print"$c\n"}
More information about the Python-list
mailing list