If I have a nested list like this:
L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]
How can I sort it from highest to lowest based on the last number in each of the sub lists without using the sorting or sorted function?
Output:
final = [['Henry', '1', '5'], ['James', '1', '2'], ['Alan', '1', '1']]
The only way I know how to do it is with the sorting function, but I would like to know how to do it without that.
You can write your own quicksort function. You can pretty much switch some signs to reverse the output:
The next step would be to make sure you're extracting the proper numbers, and make sure you can map those back to the parent list so you can drop those into the right place again — Allen's answer has a good approach:
That line basically creates a list of tuples that store the numbers we wanna sort by, and the index of that number's parent list on the overarching list. So basically, for
L
,keys = [(2, 0), (1, 1), (5, 2)]
.So you'd alter the
quicksort
function to account for all this, by creating a subfunction that can be used recursively:And with that:
Note: If there are two items with the same number in the last position those are gonna get their original relative position (to one another) in the original list reverted. See this answer for more details on tuple comparison, and note that we're sorting stuff in descending order here (otherwise, they'd just keep their original position relative to one another). So:
There are many sorting algorithms that can be implemented. Python's
sorted
builtin was thoughtfully implemented long ago by Tim Peters.However, here is another sorting option using
heapq
:By comparison, notice the similarity to
sorted
, which has several intuitive options:sorted
is generally fast with some exceptions whereheapq
is faster. See also this post for more information.