Formatting Output
Mensanator
mensanator at aol.com
Mon Jun 2 15:42:12 EDT 2008
On Jun 2, 3:38 am, Chris <cwi... at gmail.com> wrote:
> On Jun 2, 9:34 am, "victor.hera... at gmail.com"
>
> <victor.hera... at gmail.com> wrote:
> > Hi,
>
> > i am building a little script and i want to output a series of columns
> > more or less like this:
>
> > 1 5 6
> > 2 2 8
> > 2 9 5
>
> > The matter is that i don't know in advance how many columns there will
> > be. By the way, each column will be actually FLOATs, not INTs. How can
> > i do this ? Any help welcome. Regards,
>
> > Victor
>
> import sys
> float_list = [1.0, 5.0, 6.0, 2.0, 2.0, 8.0, 2.0, 9.0, 5.0]
> num_columns = 3
> for i,item in enumerate(float_list):
> sys.stdout.write('%.4f\t' % item)
> if not (i+1) % num_columns:
> sys.stdout.write('\n')
>
> Problem with this approach is it doesn't cater for instances where you
> exceed the standard 80 characters for a terminal window.
That wouldn't be a problem if being re-directed to a file.
A bigger problem would be if his list were actually
[1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0]
but he still wanted it printed
1 5 6
2 2 8
2 9 5
as if he always wants 3 rows, but doesn't know how many columns
it will take. In which case, he could do something like this:
import sys
float_list = [1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0]
num_rows = 3
num_cols = divmod(len(float_list),num_rows)
for r in xrange(num_rows):
for c in xrange(num_cols[0]):
sys.stdout.write('%.4f\t' % float_list[c*num_rows + r])
if num_cols[1]>0 and r<num_cols[1]:
sys.stdout.write('%.4f\t' % float_list[(c+1)*num_rows + r])
sys.stdout.write('\n')
1.0000 5.0000 6.0000
2.0000 2.0000 8.0000
2.0000 9.0000 5.0000
And then changing list size would merely add more columns, so
[1.0,2.0,2.0,5.0,2.0,9.0,6.0,8.0,5.0,6.6666]
would print as
1.0000 5.0000 6.0000 6.6666
2.0000 2.0000 8.0000
2.0000 9.0000 5.0000
More information about the Python-list
mailing list