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 highest length of elements in a list of list in python?

I have a list of list in Python:

list_all = [['orange', 'the dress', '5643,43245,5434,22344,34533'],
            ['pink', 'cars', '12322,4455,533,2344,24324,64466,543342'],
            ['dark pink' 'doll', '12422,4533,6446,35563'],
            ['blue', 'car', '43356,53352,546'],
            ['sky blue', 'dress', '63463,3635432,354644,6544,6444,644,74245']]

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

result = [['orange', 'the dress', '5643,43245,5434,22344,34533'],
         ['pink', 'cars', '12322,4455,533,2344,24324,64466,543342'],
         ['sky blue', 'dress', '63463,3635432,354644,6544,6444,644,74245']]

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 use sorted function

print(sorted(list_all, key=lambda e: len(e[-1].split(',')), reverse=True)[:3])

Output:

[
['pink', 'cars', '12322,4455,533,2344,24324,64466,543342'], 
['sky blue', 'dress','63463,3635432,354644,6544,6444,644,74245'], 
['orange', 'the dress', '5643,43245,5434,22344,34533']
]

The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.

More info on sorted()

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