10

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 3

11

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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 Comment

@dimay Not necessarily. I'm confused as to the order that OP wants. But I've given the option to reverse per column using a negation
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)) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.