how to find the longst element list of lists

Thomas Ploch Thomas.Ploch at gmx.net
Sun Jan 7 16:57:44 EST 2007


Michael M. schrieb:
> How to find the longst element list of lists?
> 
> I think, there should be an easier way then this:
> 
>    s1 = ["q", "e", "d"]
>    s2 = ["a", "b"]
>    s3 = ["a", "b", "c", "d"]
> 
>    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
> 
>    if len(s2) >= len(s3) and len(s2) >= len(s1):
>      sx1=s2  ## s2 ist längster
>      if len(s3) >= len(s1):
>        sx2=s3
>        sx3=s1
>      else:
>        sx2=s1
>        sx3=s3
> 
>    if len(s3) >= len(s1) and len(s3) >= len(s2):
>      sx1=s3  ## s3 ist längster
>      if len(s1) >= len(s2):
>        sx2=s1
>        sx3=s2
>      else:
>        sx2=s2
>        sx3=s1
> 
> After, the list ist sorted:
> 
>    sx1 = ["a", "b", "c", "d"]
>    sx2 = ["q", "e", "d"]
>    sx3 = ["a", "b"]
> 

I don't really get that. You have three lists, you want to sort them
after their length. You should put them into one list.
I think you should rather implement this as:

 >>> list = [a1, s2, s3]
 >>> list.sort(lambda x,y: cmp(len(y), len(x)))
 >>> list
 [['a', 'b', 'c', 'd'], ['q', 'e', 'd'], ['a', 'b']]

Thomas



More information about the Python-list mailing list