[Tutor] Re: Printing a formatted list (of lists)

Prahlad Vaidyanathan slime@vsnl.net
Tue, 30 Jul 2002 09:00:12 +0530


On Mon, 29 Jul 2002 Allyn Weaks spewed into the ether:
> Python 2.n on unix.
> I have a table that's a list of lists (values can be mixed
> numbers/text).  Is there a clean way to print a formatted list?  What I
> have works, but it seems that there ought to be a more list-oriented
> way of formatting the list part.  Or is this one of those places where
> one accepts the explicit loop?  I've tried out list comprehension
> variations 'til I'm dizzy with nothing but assorted errors.
> for j in range(len(table)):
>     print `table[j]`.rjust(columnwidth),

How about this :

def print_list (list_of_lists) :
    column_width = 8
    separator = ","
    line_break = "\n"
    out_str = ""
    ## Explicit loop
    ## This makes it clearer than when list comprehension
    ## is used, IMHO.
    for inner_list in list_of_lists :
        for l in inner_list :
            ## The str() function will convert all values
            ## be it numbers/text, into the corresponding
            ## string form.
            out_str += str(l).rjust(column_width) + separator
        ## Adds the line break
        out_str += line_break
    return out_str

if __name__ == "__main__":
    l = [ [1,2,3,complex(1,1)], [5,6,7,8.12], [10,11,12,"string"] ]
    print print_list(l)


Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

The beauty of a pun is in the "Oy!" of the beholder.