This is a job for itemgetter
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
It is also possible to use a lambda function here, however the lambda function is slower in this simple case
Answer from John La Rooy on Stack OverflowThis is a job for itemgetter
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
It is also possible to use a lambda function here, however the lambda function is slower in this simple case
in place
>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])
not in place using sorted:
>>> sorted(l, key=lambda x: x[2])
Sorting list of lists
How do I sort a list with sublists with multiple ascending and descending criteria?
PySpark - How to deal with list of lists as a column of a dataframe
[Haskell] Finding the shortest list in a list of lists
Videos
For example, if I have a list :
list = [ [-10, 1, 3], [2, -5, 29], [3, -5, 0], [0, 0, -1] ]
And I want to sort the list with the following criteria in order :
For i in list :
-
sort
i[2](in ascending order) -
sort
i[0](in descending order) -
sort
i[1](in ascending order)
I've tried rearranging by using list comprehension and *-1 on the index I want to sort in descending order, then sort the rearranged list ( ex : newlist = [ [i[2], -i[0], i[1]] for i in list ] then newlist.sort() ) However, *-1 for descending order doesn’t work since some numbers are already negative, so that’s like where I’m stuck with. Any idea how to do this?
By the way, I cannot use dict, numpy, tuple, set or import any libraries since this is my college homework and my professor doesn’t allow us to use any of those.