Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort nested list data in python

I am trying to sort a nested list in python(3.8.5). I have a list like -

[['1', 'A', 2, 5, 45, 10],
 ['2', 'B', 8, 15, 65, 20],
 ['3', 'C', 32, 35, 25, 140],
 ['4', 'D', 82, 305, 75, 90],
 ['5', 'E', 39, 43, 89, 55],
 ]

and I want to sort like this -

[['4', 'D', 82, 305, 75, 90],
 ['5', 'E', 39, 43, 89, 55],
 ['3', 'C', 32, 35, 25, 140],
 ['2', 'B', 8, 15, 65, 20],
 ['1', 'A', 2, 5, 45, 10],
 ]

it has sorted by column with index 2. and more like this according to index. start with index 2 and so on. I mean it has sorted according to columns. so could I do this.

like image 851
Lokesh sahu Avatar asked Apr 24 '26 07:04

Lokesh sahu


1 Answers

Try this:

lst = [['1', 'A', 2, 5, 45, 10],
 ['2', 'B', 8, 15, 65, 20],
 ['3', 'C', 32, 35, 25, 140],
 ['4', 'D', 82, 305, 75, 90],
 ['5', 'E', 39, 43, 89, 55],
 ]

lst = sorted(lst, key=lambda x: x[2], reverse=True)
print(lst)
like image 124
dimay Avatar answered Apr 30 '26 23:04

dimay