Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17145

Re: Using methodcaller in a list sort - any examples anywhere?

From Peter Otten <__peter__@web.de>
Subject Re: Using methodcaller in a list sort - any examples anywhere?
Followup-To gmane.comp.python.general
Date 2011-12-13 17:13 +0100
Organization None
References <hm8kr8-uge.ln1@chris.zbmc.eu>
Newsgroups comp.lang.python
Message-ID <mailman.3602.1323792823.27778.python-list@python.org> (permalink)

Followups directed to: gmane.comp.python.general

Show all headers | View raw


tinnews@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"))

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Using methodcaller in a list sort - any examples anywhere? tinnews@isbd.co.uk - 2011-12-13 15:48 +0000
  Re: Using methodcaller in a list sort - any examples anywhere? Peter Otten <__peter__@web.de> - 2011-12-13 17:13 +0100
    Re: Using methodcaller in a list sort - any examples anywhere? tinnews@isbd.co.uk - 2011-12-13 16:48 +0000
  Re: Using methodcaller in a list sort - any examples anywhere? Tim Chase <python.list@tim.thechases.com> - 2011-12-13 10:08 -0600

csiph-web