Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #17152
| From | tinnews@isbd.co.uk |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Using methodcaller in a list sort - any examples anywhere? |
| Date | 2011-12-13 16:48 +0000 |
| Message-ID | <j8ckr8-b84.ln1@chris.zbmc.eu> (permalink) |
| References | <hm8kr8-uge.ln1@chris.zbmc.eu> <mailman.3602.1323792823.27778.python-list@python.org> |
Peter Otten <__peter__@web.de> wrote:
> 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"))
>
OK, thanks, just what I wanted.
--
Chris Green
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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