sort(): Giving third argument?

Eric Brunel eric.brunel at pragmadev.com
Fri Mar 21 05:11:18 EST 2003


Thomas Guettler wrote:
> Hi!
> 
> If I have a list of IDs and a hash which maps
> each ID to a name:
> 
> ids=[1, 2, 3, 4]
> 
> names={
>  1: "foo",
>  2: "bar",
>  ...}
> 
> I can't do the following:
> 
> def mycmp(a, b):
>     return cmp(names[a], names[b])
> 
> ids.sort(mycmp)
> 
> since "name" is unkown in mycmp.
> 
> What's the best solution?

def dictCompare(key1, key2, theDict):
   return cmp(theDict[key1], theDict[key2])
ids.sort(lambda x, y, d=names: dictCompare(x, y, d))

or even:

ids.sort(lambda x, y, d=names: cmp(d[x], d[y]))

(There may be a better solution if your Python version supports nested scopes, 
but mine doesn't...)

So no need to give sort a third argument, which is a bit awkward for this 
particular puprpose (at least IMHO)

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com





More information about the Python-list mailing list