How to find the top 3 lists in a list of list based on the last element in python?

Question:

I have a list of list in Python:

list_all = [['orange', 'the dress', '127456'],
            ['pink', 'cars', '543234'],
            ['dark pink' 'doll', '124098'],
            ['blue', 'car', '3425'],
            ['sky blue', 'dress', '876765']]

I want to return top 3 lists which have the highest count of numbers in the last part. Like this:

result = [['sky blue', 'dress', '876765'],
         ['pink', 'cars', '543234'],
         ['orange', 'the dress', '127456']]

I just cannot find the logic to do this. I have tried a lot, but just got stuck with one line of code:

for each in list_all:
    if len(each[-1].split(','))

How do I solve this?

Asked By: ssdn

||

Answers:

You can do it with sorted():

sorted(list_all, key = lambda x: int(x[-1]))[-3:][::-1]

Output:

[['sky blue', 'dress', '876765'],
 ['pink', 'cars', '543234'],
 ['orange', 'the dress', '127456']]
Answered By: Nin17

Use a lambda

Modification from: How to sort a 2D list?

result  = sorted(list_all ,key=lambda l:int(l[-1]), reverse=True)[:3]

This returns

[['sky blue', 'dress', '876765'],
 ['pink', 'cars', '543234'],
 ['orange', 'the dress', '127456']]
Answered By: Xinurval
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.