You can write your own quicksort function. You can pretty much switch some signs to reverse the output:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)/2]
left = [x for x in arr if x > pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x < pivot]
return quicksort(left) + middle + quicksort(right)
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:
L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]
keys = [(int(v[-1]),k) for k,v in enumerate(L)] # This line here
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:
def quicksort(arr):
# Put the actual sorting function into a subfunction that can be called recursively
def subsort(arr2):
if len(arr2) <= 1:
return arr2
pivot = arr2[len(arr2)/2]
left = [x for x in arr2 if x > pivot]
middle = [x for x in arr2 if x == pivot]
right = [x for x in arr2 if x < pivot]
return subsort(left) + middle + subsort(right)
# Get the value-key pairs and sort them
keys = [(int(v[-1]),k) for k,v in enumerate(L)]
keys = subsort(keys)
# Do the mapping back to the original array fed into the main function
final = []
for i in keys:
final.append(arr[i[1]])
return final
And with that:
>>> L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]
>>> quicksort(L)
[['Henry', '1', '5'], ['James', '1', '2'], ['Alan', '1', '1']]
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:
>>> L = [['Simon', '1', '2'], ['Henry', '1', '5'], ['Finn', '1', '2']
>>> quicksort(L)
[['Henry', '1', '5'], ['Finn', '1', '2'], ['Simon', '1', '2']]