in need of some sorting help

Kent Johnson kent at kentsjohnson.com
Fri Mar 3 07:05:22 EST 2006


ianaré wrote:
>> you did make me understand  a way to sort this thing finally: sort by
> base path then by full path, which is how i came up with:
> 
> files.sort(key=lambda x: x.lower())
> files.sort(key=lambda x: os.path.dirname(x))
> 
> well actually i am sorting first by full name, then by base, taking
> advantage of python2.4's stable sort().
> 
> If you can think of a more efficient (faster) way of doing this please
> let me know. i'm not crazy about having to sort this list twice, it can
> get pretty big (50,000 entries)

Use a key function that returns a tuple of the two values you want to 
sort on:
def make_key(f):
   return (os.path.dirname(f), f.lower())

files.sort(key=make_key)

Kent



More information about the Python-list mailing list