Using methodcaller in a list sort - any examples anywhere?

tinnews at isbd.co.uk tinnews at isbd.co.uk
Tue Dec 13 11:48:51 EST 2011


Peter Otten <__peter__ at web.de> wrote:
> tinnews at isbd.co.uk wrote:
> 
> > I want to sort a list of 'things' (they're fairly complex objects) by
> > the contents of one of the fields I can extract from the 'things'
> > using a Python function.
> > 
> > So I have a list L which is a list of objects of some sort.  I can
> > output the contents of a field in the list as follows:-
> > 
> >     for k in L:
> >         print k.get_property('family-name')
> > 
> > How can I sort the list first?  As I said it seems like a methodcaller
> > is the answer but I don't see how.  I want to sort the list of objects
> > not just produce a sorted list of names.
> 
> The most obvious way is to use a custom function
> 
> def get_family_name(obj):
>     return obj.get_property("family-name")
> L.sort(key=get_family_name)
> 
> However, since you already know about methodcaller
> 
> """ 
> class methodcaller(builtins.object)
>  |  methodcaller(name, ...) --> methodcaller object
>  |
>  |  Return a callable object that calls the given method on its operand.
>  |  After, f = methodcaller('name'), the call f(r) returns r.name().
>  |  After, g = methodcaller('name', 'date', foo=1), the call g(r) returns
>  |  r.name('date', foo=1).
> """"
> 
> L.sort(key=methodcaller("get_property", "family-name"))
> 
OK, thanks, just what I wanted.

-- 
Chris Green



More information about the Python-list mailing list