[Tutor] calculating a sort key and operator.attrgetter()

Vincent Davis vincent at vincentdavis.net
Wed Jul 1 16:36:09 CEST 2009


Thanks for the help, Looks like I will define a function. And yes you are
right self.does_observe is constant so it will not affect the outcome.

Thanks again
Vincent Davis



On Tue, Jun 30, 2009 at 11:15 PM, Kent Johnson <kent37 at tds.net> wrote:

> On Tue, Jun 30, 2009 at 11:39 PM, Vincent Davis<vincent at vincentdavis.net>
> wrote:
> > I have a class with an attribute which is a list "rank_list" this is a
> list
> > of instances f another class that has attributes "quality, is_observed"
> > if I want to sort the list by the attribute "quality" I can just use,
> > self.rank_list.sort(key=operator.attrgetter('quality'))
> > But I want to sort like this.
> > self.rank_list.sort(key=(operator.attrgetter('quality') *
> > operator.attrgetter('is_observed') * self.does_observe))
> > Will this work or is there a better way?
>
> That won't work because attrgetter() returns a function and you can't
> multiply functions. What you can do is define your own function that
> returns the value you want for the key and use that for the sort. I'm
> leaving out self.does_observe because that won't change for the list
> items, wil it?
>
> def make_key(item):
>  return item.quality * item.is_observed
>
> self.rank_list.sort(key=make_key)
>
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090701/5d1a464f/attachment-0001.htm>


More information about the Tutor mailing list