Printing Columns

Steven Taschuk staschuk at telusplanet.net
Tue Apr 15 17:32:05 EDT 2003


Quoth Lindstrom Greg - glinds:
  [...]
> myList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
  [...]
> 	A	D	G
> 	B	E	H
> 	C	F
> 
> problem is, the code (all 12 lines) is a bit convoluted and would not be
> easy for the next person using it to figure out (and in my mind,
> maintainability is priority one; that's why I use Python).  I would like to
> know if there is a "pythonic" way to do this. So, here are the specs....
> 
> Given a list of length N with 0<=N<=infinity and a number of columns, C (C>0
> and may be less than N), how do we print out the elements of the list in the
> above (column major?) form?

N might be infinite?  That introduces some difficulties.  I'll
assume you meant 0 <= n < infinity.

You don't specify which of these arrangements is preferred:
    0  3  6  8            0  3  6  9
    1  4  7  9            1  4  7
    2  5                  2  5  8
I'll assume the former.

The most straightforward method I can think of is this:

    def chop(lst, n):
        """Chop lst into sublists of n items."""
        return [lst[i:i+n] for i in range(0, len(lst), n)]

    def columnize(lst, n):
        """Arrange the elements of lst into n columns."""
        # assemble long & short columns
        q, r = divmod(len(lst), n)
        longcount = r # number of long columns
        longlen = q + 1 # length of long columns
        shortlen = q # length of short columns
        longcols = chop(lst[:longcount*longlen], longlen)
        shortcols = chop(lst[longcount*longlen:], shortlen)
        # pad short columns
        shortcols = [c + [None] for c in shortcols]
        # transpose
        rows = map(list, zip(*(longcols + shortcols)))
        # unpad short columns
        del rows[-1][longcols:]
        return rows

Example:

    for row in columnize(range(37), 5):
        print '\t'.join(map(str, row))

    0       8       16      23      30
    1       9       17      24      31
    2       10      18      25      32
    3       11      19      26      33
    4       12      20      27      34
    5       13      21      28      35
    6       14      22      29      36
    7       15

-- 
Steven Taschuk                            staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
                                                  (Kinsley's Law)





More information about the Python-list mailing list