[Tutor] print as columns [using apply()]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 17 Jul 2001 14:23:06 -0700 (PDT)


On Tue, 17 Jul 2001, Michael P. Reilly wrote:

> > 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?
> 
> Actually, none of these work.  The max of a list of lists is to find out
> which list is greater, by component, not the longer.
> 
> >>> a = [1, 2, 3]
> >>> b = [3, 4, 5, 6]
> >>> max(a, b)
> [3, 4, 5, 6]
> >>> c = [7, 8, 9]
> >>> max(b, c)
> [7, 8, 9]
> 
> You probably want to use: reduce(max, map(len, seq_o_lists))
> 
> >>> reduce(max, map(len, (a, b, c)))


This problem shows one instance where apply() might be useful: max() can
take in as many arguments as we can feed into it:

###
>>> max(3, 1, 4, 1, 5, 9, 2, 6)
9
###

so we don't really even need the reduce if we use the apply() function:

###
apply(max, map(len, (a, b, c)))
###


If you have any questions, feel free to ask!