how to find the longst element list of lists

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jan 7 23:11:59 CET 2007


Michael M. a écrit :
> How to find the longst element list of lists?

For what definition of "find" ? You want the lenght of the longest 
sublist, it's index, or a reference to it ?

> I think, there should be an easier way then this:
> 
>   s1 = ["q", "e", "d"]
>   s2 = ["a", "b"]
>   s3 = ["a", "b", "c", "d"]

Err... this makes three distinct lists, not a list of lists.

>   if len(s1) >= len(s2) and len(s1) >= len(s3):
>     sx1=s1  ## s1 ist längster
>     if len(s2) >= len(s3):
>       sx2=s2
>       sx3=s3
>     else:
>       sx2=s3
>       sx3=s2
> 
(snip repeated code)

Looks like it would be time to learn how to factor out repetitions...

> After, the list ist sorted:
> 
>   sx1 = ["a", "b", "c", "d"]
>   sx2 = ["q", "e", "d"]
>   sx3 = ["a", "b"]
> 

This is still not a list of lists. Now for the answer, sorted() is your 
friend:

print sorted([s1, s2, s3], key=list.__len__, reverse=True)
=> [['a', 'b', 'c', 'd'], ['q', 'e', 'd'], ['a', 'b']]

# Or if you really want sx1, sx2 and sx3:
sx1, sx2, sx3 = sorted([s1, s2, s3], key=list.__len__, reverse=True)


Is that easier enough ?-)



More information about the Python-list mailing list