Daymor
Daymor

Reputation: 95

Ordering a list of lists by lists len

I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

 orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else: 
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1    

 return orderedpaths

the error I'm getting is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax

I have no idea why.

Upvotes: 1

Views: 8694

Answers (3)

ikostia
ikostia

Reputation: 7597

You can also use this pretty piece of code :) :

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, lambda x,y: 1 if len(x)>len(y) else -1 if len(x)<len(y) else 0)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]

and swap 1 with -1 if you want another sorting order.

As commenters notice this code works only in python 2.x. There is some prettier code which works in python 3.x as well:

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, key = len)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]

Upvotes: -1

Shawn Chin
Shawn Chin

Reputation: 86924

As stated in eumiro's answer using sorted() is the way to go.

Note that sorted() (as well as list.sort(key=..)) was only introduced in Python 2.4. If you're in my boat and have to make do with <2.4, you could create your own version. Rough example:

import inspect
def my_sorted(in_list, key=lambda x:x):

    # basic error checking
    if not is_instance(in_list, list):
        raise ValueError("expecting 1st argument to be a list")

    if not inspect.isroutine(key):
        raise ValueError("key must be a function/method")

    # convert to [ (key(item1), item1), .... ]
    key_map = map(lambda x: (key(x),x), in_list)
    # standard sort, while effectively sort by key(item)
    key_map.sort()

    # convert back original format and return
    return [x for _,x in key_map]

You can then use it as such:

orderedpaths = my_sorted(paths, key=len)

Upvotes: 2

eumiro
eumiro

Reputation: 213005

Your problem was the number of brackets in:

smallest=(len(paths[c])

and in:

if(len[paths[c])<smallest):

and also in:

if(len[paths[c])<smallest):

To sort paths according to their length, you can try this:

orderedpaths = sorted(paths, key=len)

Here's the documentation for sorted.

Upvotes: 22

Related Questions