Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44885

Re: formatted output

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: formatted output
Date 2013-05-07 08:42 -0400
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-8514D9.08422007052013@news.panix.com> (permalink)
References <add22437-64a4-4dfb-b6d9-28832e7698b4@googlegroups.com>

Show all headers | View raw


In article <add22437-64a4-4dfb-b6d9-28832e7698b4@googlegroups.com>,
 Sudheer Joseph <sjo.india@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

formatted output Sudheer Joseph <sjo.india@gmail.com> - 2013-05-07 05:00 -0700
  Re: formatted output Roy Smith <roy@panix.com> - 2013-05-07 08:42 -0400
    Re: formatted output Peter Otten <__peter__@web.de> - 2013-05-07 15:28 +0200

csiph-web