sort(): Giving third argument?

Max M maxm at mxm.dk
Fri Mar 21 05:43:32 EST 2003


Thomas Guettler wrote:

> 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])


A "simple" and generic solution would be to create a callable class:

     ids=[1, 2, 3, 4]

     names={
      1: "foo",
      2: "bar",
      3: "spam",
      4: "foobar",
     }

     class Sorter:

         def __init__(self, names):
             self.names = names

         def __call__(self, x, y):
             return cmp(self.names[x], self.names[y])

     ids.sort(Sorter(names))
     print ids

     >>> [2, 1, 4, 3]

-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list