Re: [Tutor] calculating a sort key and operator.attrgetter()
On Tue, Jun 30, 2009 at 11:39 PM, Vincent Davisvinc...@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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calculating a sort key and operator.attrgetter()
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 ken...@tds.net wrote: On Tue, Jun 30, 2009 at 11:39 PM, Vincent Davisvinc...@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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] calculating a sort key and operator.attrgetter()
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? Thanks Vincent Davis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor