Search code examples
pythonlistsortingreturnelement

How to sort and filter a list in Python?


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!!


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