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.
CodePudding user response:
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']]
CodePudding user response:
Use a lambda
Modification from: How to sort a 2D list?
result = sorted(list_all ,key=lambda l:l[-1], reverse=True)[:3]
This returns
[['sky blue', 'dress', '876765'],
['pink', 'cars', '543234'],
['orange', 'the dress', '127456']]