Home > OS >  How to find the list in Python?
How to find the list in Python?

Time:06-01

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:

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.

CodePudding user response:

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()

CodePudding user response:

Here is a handy one-liner:

print(sorted(all_list, key=lambda l: len(l[-1].split(',')))[:-3])
  • Related