Python 2d list sort

I have the following list type

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 to sort the function in Python. But gives me a "TypeError": the "float" object is unsigned. Please help me solve this problem.

+17
source share
2 answers

You can use 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 in another way:

 >>> sorted(li,key=lambda l:l[1]) [[1, 0.23], [5, 0.27], [4, 0.31], [2, 0.39]] 
+33
source

To sort the list of lists in the second column, use operator.itemgetter() for convenience and clarity:

 from operator import itemgetter outputlist = sorted(inputlist, key=itemgetter(1), reverse=True) 

or to sort by location:

 from operator import itemgetter inputlist.sort(key=itemgetter(1), reverse=True) 

itemgetter() slightly faster than using lambda for a 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 will only see your exception if you had floating point values ​​in your input list 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, the Python 2 error message is slightly different, as a result, instead of TypeError: 'float' object has no attribute '__getitem__' ).

This is because the itergetter(1) call is applied to all elements of the external list, but only works with nested ordered sequences, and not with one added floating point value.

+13
source

Source: https://habr.com/ru/post/952941/


All Articles