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

Kent Johnson kent37 at tds.net
Wed Jul 1 07:15:10 CEST 2009


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


More information about the Tutor mailing list