I have following type of list
lst = [
[1, 0.23],
[2, 0.39],
[4, 0.31],
[5, 0.27],
]
I want to sort this in descending order of the second column. I tried built-in sorted()
function in python, but it gives me 'TypeError' : 'float' object is unsubscriptable
.
To sort a two-dimensional list in Python use the sort() list method, which mutates the list, or the sorted() function, which does not. Set the key parameter for both types using a lambda function and return a tuple of the columns to sort according to the required sort order.
You can custom the sort behaviour by pass a key and reverse. sorted will return a new list. If in-place sort wanted, use list. sort .
In a 2D array, a cell has two indexes one is its row number, and the other is its column number. Sorting is a technique for arranging elements in a 2D array in a specific order. The 2D array can be sorted in either ascending or descending order.
There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.
You can use a lambda:
>>> li=[[1, 0.23],
... [2, 0.39],
... [4, 0.31],
... [5, 0.27]]
>>> sorted(li,key=lambda l:l[1], reverse=True)
[[2, 0.39], [4, 0.31], [5, 0.27], [1, 0.23]]
Or the other way:
>>> sorted(li,key=lambda l:l[1])
[[1, 0.23], [5, 0.27], [4, 0.31], [2, 0.39]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With