[Tutor] print as columns
Mike Serpa
onav@yahoo.com
Tue, 17 Jul 2001 10:06:52 -0700 (PDT)
>
> I have a couple suggestions regarding your printListColumns:
>
> 1) you can find the longest in a list of lists by using the
> reduce function which keeps applying the function to
> successive pairs of elements from a list:
>
> n=len(reduce(lambda a,b:max(a,b),l))
> --- ------------------- -
> ^ ^ ^->the list of lists (called Lists
> in
> your program)
> | |
> | |_ the function which returns the longer of two lists
> |
> |_ when the reduce is done we will know the longest list, len
> gives the
> length of it
>
> Example:
>
> a=[1,2,3,4]
> b=[5,6,7]
> c=[8,9,10,11,12]
>
> n=len( reduce( lambda a,b:max(a,b), [a,b,c] ))
>
> n is 5
Couldn't we shorten this to:
n=len(max(lists))
It seems that everything I figure out how to do is already in a module
somewhere. Question for expert Python coders (or any lang.) Do you
ever get to the stage where you don't have to constantly look things
up in the lang docs?
>
> 2) Instead of padding, you might consider using the try/except
> construction to not print the list elements that don't
> exist. Here's how it looks for a list of 3 elements which is to be
> printed in 5 rows.
>
> for j in range(5):
> try:
> print str(l[j].ljust(20), #if l[j] exists, print it
> except:
> print ''.ljust(20) #otherwise format a null string
>
> Thanks for the thought provoking post.
>
So I don't have to lace them then.
So we get:
def printListColumns(*lists):
longestLength=len(max(lists))
for row in range(longestLength): # number of rows
for column in lists: # number of columns
try:
print str(column[row]).ljust(20), # print if exists
except:
print ''.ljust(20) # blank if not
print
Great!
We've gone from 20 lines to 15 to 9. More importantly it's now much
simpler.
The only thing I can think to add is a max number of columns so it
doesn't go off the screen. Or if columns is > 4 then split into two
tables. Or adjust columns to largest element, etc. Don't need to yet
for what I'm using if for, but will be easier now. Thanks.
Mike
__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail
http://personal.mail.yahoo.com/