Printing Columns

Jimmy Retzlaff jimmy at retzlaff.com
Tue Apr 15 20:34:32 CEST 2003


Lindstrom Greg - glinds (Greg.Lindstrom at acxiom.com) wrote:
>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?

Here's a relatively straightforward approach:

import math

def printInColumns(items, numberOfColumns):
    numberOfRows = int(math.ceil(1.0*len(items)/numberOfColumns))
    for row in range(numberOfRows):
        for column in range(numberOfColumns):
            index = column*numberOfRows + row
            if index < len(items):
                print items[index], '\t',
        print

printInColumns(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 3)


If you test this a bit you can find some trouble spots (for the problem
in general). For example how do you print 8 items in 7 columns? The
above approach would result in:

A 	C 	E 	G 	
B 	D 	F 	H 	

Is there actually a way to use all 7 columns?

Jimmy





More information about the Python-list mailing list