Sort Nested List Data in Python

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.

0

3 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)

If you want to sort a list like that, just give sorted a key:

sorted_list = sorted([['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]], key=lambda lst: lst[2], lst[1], ....)

For numerical values, you can even include a negative sign (-lst[1]) to reverse the ordering for an individual column

1

Code to sort the tuples using second element of sub-list in-place way to sort using sort():

def sort(sub_li): 
    # reverse = None (Sorts in Ascending order) 
    # key is set to sort using second element of 
    # sublist lambda has been used 
    sub_li.sort(key = lambda x: x[2],reverse=True) 
    return sub_li 

# Driver Code 
sub_li =[['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],
    ]
print(Sort(sub_li)) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.