formatted output

Peter Otten __peter__ at web.de
Tue May 7 09:28:27 EDT 2013


Roy Smith wrote:

> In article <add22437-64a4-4dfb-b6d9-28832e7698b4 at googlegroups.com>,
>  Sudheer Joseph <sjo.india at gmail.com> wrote:
> 
>> Dear members,
>>             I need to print few arrays in a tabular form for example
>>             below array IL has 25 elements, is there an easy way to print
>>             this as 5x5 comma separated table? in python
>> 
>> IL=[]
>> for i in np.arange(1,bno+1):
>>        IL.append(i)
>> print(IL)
>> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> in fortran I could do it as below
>> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> integer matrix(5,5)
>>        in=0
>>       do, k=1,5
>>       do, l=1,5
>>        in=in+1
>>       matrix(k,l)=in
>>       enddo
>>       enddo
>>       m=5
>>       n=5
>>       do, i=1,m
>>       write(*,"(5i5)") ( matrix(i,j), j=1,n )
>>       enddo
>>       end
>>  
> 
> Excellent.  My kind of programming language!  See
> http://www.python.org/doc/humor/#bad-habits.
> 
> Anyway, that translates, more or less, as follows.
> 
> Note that I'm modeling the Fortran 2-dimensional array as a dictionary
> keyed by (k, l) tuples.  That's easy an convenient, but conceptually a
> poor fit and not terribly efficient.  If efficiency is an issue (i.e.
> much larger values of (k, l), you probably want to be looking at numpy.
> 
> Also, "in" is a keyword in python, so I changed that to "value".
> There's probably cleaner ways to do this. I did a pretty literal
> transliteration.
> 
> 
> matrix = {}
> value = 0
> for k in range(1, 6):
>    for l in range(1, 6):
>       value += 1
>       matrix[(k, l)] = value
> 
> for i in range(1, 6):
>    print ",".join("%5d" % matrix[(i, j)] for j in range(1, 6))
> 
> This prints:
> 
>     1,    2,    3,    4,    5
>     6,    7,    8,    9,   10
>    11,   12,   13,   14,   15
>    16,   17,   18,   19,   20
>    21,   22,   23,   24,   25

Or, as the OP may be on the road to numpy anyway:

>>> import numpy
>>> a = numpy.arange(1, 26).reshape(5, 5)
>>> a
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])
>>> import sys
>>> numpy.savetxt(sys.stdout, a, delimiter=", ", fmt="%5d")
    1,     2,     3,     4,     5
    6,     7,     8,     9,    10
   11,    12,    13,    14,    15
   16,    17,    18,    19,    20
   21,    22,    23,    24,    25





More information about the Python-list mailing list