Can python list sort key function take index instead of an element?

Question:

Take a look at this code:

points = [...]
properties = [compute_point_property(point) for point in points]
points.sort(?)

Here I have a list of points, and I compute a property of each point. Then I need to sort the points by their corresponding property value.
The problem is that the compute_point_property is computationally expensive, so I don’t want to call it more that needed. And I also would need further to use the properties of the points. That means I cannot just use

points.sort(key=compute_point_property)

Because in this case the result of the compute_point_property is not stored in a variable for me to use further.

In my case, the elements (points) are hashable, so I can put them in dict, and use it like this:

points = [...]
properties = [compute_point_property(point) for point in points]
points_properties = dict(zip(points, properties))
points.sort(key=lambda point: points_properties[point])

It would work, but it seems wrong and unnecessarily. And it works only for hashable list elements. I want to learn how to do it with any list element type, whether it hashable or not.

Another idea is to put both point and its corresponding property into a tuple, and have a list of these tuples. Then sort the list of tuples by the second tuple element (the point property). Then extract the points from the list of tuples.

points = [...]
properties = [compute_point_property(point) for point in points]
points_properties = list(zip(points, properties))
points_properties.sort(key=lambda x: x[1])
points = [x[0] for x in points_properties]

Also works, but creates a list of tuples and extracts points from the list of tuples, so it does more than actually needed.

It would be great if the list.sort‘s key function would take an element index instead of the element value as an argument. In this case, it would be possible to do it like this:

points = [...]
properties = [compute_point_property(point) for point in points]
points.sort(key=lambda index: properties[index])

What would be the best way to sort the list while storing the computed properties?
Thanks in advance!

Asked By: g00dds

||

Answers:

The solution is simpler than you think:

sorted_pairs = sorted((compute_point_property(point), point) for point in points)
Answered By: kosciej16
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.