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 sort a list in Python using two conditions?

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:

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

result= []
result += sorted(x_list, key=lambda x: int(x[-1]))[:3]

Can anyone plz help me to solve this? Thank you very much!!

>Solution :

I would first filter the list to only retain values where first element is greater than 400, and then sort the final result by ascending order based on last element, as you originally had it. For example:

x_list = [['422', '324', '733443'], ['342', '654', '674335'],
         ['953', '456', '828854'], ['345', '886', '446678'],
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

x_list2 = [x for x in x_list if int(x[0]) > 400]
x_list2.sort(key=lambda x: x[2])
x_list2 = x_list2[:3]

print(x_list2)
# [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]

Or you can also sort and filter in a single step as well:

x_list = [['422', '324', '733443'], ['342', '654', '674335'],
         ['953', '456', '828854'], ['345', '886', '446678'],
         ['3224', '533', '654333'], ['7545', '5567', '369990']]

x_list2 = sorted((x for x in x_list if int(x[0]) > 400), key=lambda x: x[2])[:3]

print(x_list2)
# [['7545', '5567', '369990'], ['3224', '533', '654333'], ['422', '324', '733443']]
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