2

I've got a list of objects, that have a function which does some calculations on several member variables and returns a value. I want to sort the list according to this return value.

I've found how to sort a list of objects by member variables but I want to keep them private (_variable_name).

Is there an easy way to accomplish this similar to the method of sorting the list directly by the members of the objects?

1 Answer 1

7

Just use the key argument to the sorted() function or list.sort() method:

sorted_list = sorted(list_of_objects, key=function_that_calculates)

The function_that_calculates is called for each entry in list_of_objects and its result informs the sort.

If you meant that each object has a method, you can use a lambda or the operator.methodcaller() object to call the method on each element:

sorted_list = sorted(list_of_objects, key=lambda obj: obj.method_name())

or

from operator import methodcaller

sorted_list = sorted(list_of_objects, key=methodcaller('method_name'))

Note that in Python, there is no such thing as a private attribute; your sorting function can still just access it. The leading underscore is just a convention. As such, sorting by a specific attribute can be done with either a lambda again, or using the operator.attrgetter() object:

sorted_list = sorted(list_of_objects, key=lambda obj: obj._variable_name)

or

from operator import attrgetter

sorted_list = sorted(list_of_objects, key=attrgetter('_variable_name'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer the sorted(list_of_objects, key=lambda obj: obj.method_name()) way did work out very well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.