To sort a list of lists on the second column, use operator.itemgetter()
for ease and clarity:
from operator import itemgetter
outputlist = sorted(inputlist, key=itemgetter(1), reverse=True)
or, to sort in-place:
from operator import itemgetter
inputlist.sort(key=itemgetter(1), reverse=True)
itemgetter()
is a little faster than using a lambda
for the task.
Demo:
>>> from operator import itemgetter
>>> inputlist = [
... [1, 0.23],
... [2, 0.39],
... [4, 0.31],
... [5, 0.27],
... ]
>>> sorted(inputlist, key=itemgetter(1), reverse=True)
[[2, 0.39], [4, 0.31], [5, 0.27], [1, 0.23]]
You'd only see your exception if you had floating point values in your inputlist directly:
>>> inputlist.append(4.2)
>>> inputlist
[[1, 0.23], [2, 0.39], [4, 0.31], [5, 0.27], 4.2]
>>> sorted(inputlist, key=itemgetter(1), reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not subscriptable
(for Python 3; Python 2's error message is slightly different, resulting in TypeError: 'float' object has no attribute '__getitem__'
instead).
This is because the itergetter(1)
call is applied to all elements in the outer list but only works on nested ordered sequences, not on the one floating point value now added.