Saif
Saif

Reputation: 21

Sort a nested list in python by inner list number

say I have a nested list such as this,

[
    ['a', [2, 3, 7]], 
    ['j', [63, 4, 0]], 
    ['c', [1, 155, 10]], 
    ['z', [0, 77, 7]], 
    ['f', [100, 42, 9]]
]

How do sort this by the chosen largest number in the innermost list? For instance, if we wanted to sort it by the first integer in each element's list from largest to smallest, the result would be

[
    ['f', [100, 42, 9]], 
    ['j', [63, 4, 0]], 
    ['a', [2, 3, 7]], 
    ['c', [1, 155, 10]], 
    ['z', [0, 77, 7]]
]

Upvotes: 0

Views: 4673

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

You need to use a key that extracts the value by which to sort; here that is element[1][0]:

sorted(inputlist, key=lambda e: e[1][0], reverse=True)

The reverse=True is there to sort from largest to smallest.

Upvotes: 4

Related Questions