1

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

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

Pranav Hosangadi
  • 17,542
  • 5
  • 40
  • 65
ssdn
  • 37
  • 4

2 Answers2

2

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']]
Nin17
  • 1,484
  • 1
  • 3
  • 8
  • Good answer! As the OP is new to python, maybe you want to explain why the code works. I can imagine especially the negative indexing is new to them. – Kim May 31 '22 at 13:20
  • I think others have already done that better than I would: https://stackoverflow.com/questions/493046/i-dont-understand-slicing-with-negative-bounds-in-python-how-is-this-supposed https://stackoverflow.com/questions/509211/understanding-slicing – Nin17 May 31 '22 at 13:25
  • It's still best to include some explanation here, and link to that for further reading (because you don't want your answer to become unhelpful if that answer is modified or deleted) – Pranav Hosangadi May 31 '22 at 14:56
  • Also instead of the slicing and reversing shenanigans, you can just do `sorted(..., reverse=True)[:3]` – Pranav Hosangadi May 31 '22 at 14:57
  • @PranavHosangadi feel free to edit it – Nin17 May 31 '22 at 16:59
2

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']]
Xinurval
  • 44
  • 3