I have a list of list in Python that I want to sort based on two categories. The sorted list should have the lowest number in the last position and also the first element has to be greater than 400. I want to return the top 3 from the list.
x_list = [['422', '324', '733443'], ['342', '654', '674335'],
['953', '456', '828854'], ['345', '886', '446678'],
['3224', '533', '654333'], ['7545', '5567', '369990']]
It should return like this:
result = [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]
I have tried using the following code, but cannot combine the two conditions to sort the list:
result= []
result += sorted(x_list, key=lambda x: int(x[-1]))[:3]
Can anyone plz help me to solve this? Thank you very much!!
Consider this code:
filter_first = [el for el in x_list if int(el[0]) > 400]
sorted(filter_first, key=lambda el: el[-1])
This gives me
[['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443'], ['953', '456', '828854']]
which is different from what you claimed you wanted the output to be, but I think it meets all your stated requirements. Can you explain the '953' sublist?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With