Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Please help me to solve this. I am new to Python and learning it. Thank you so much.

>Solution :

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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading