Search code examples
python-3.xsortingcomparison

Can a comparator function be made from two conditions connected by an 'and' in python (For sorting)?


I have a list of type:

ans=[(a,[b,c]),(x,[y,z]),(p,[q,r])]

I need to sort the list by using the following condition :

if (ans[j][1][1]>ans[j+1][1][1]) or (ans[j][1][1]==ans[j+1][1][1] and ans[j][1][0]<ans[j+1][1][0]):
     # do something (like swap(ans[j],ans[j+1]))

I was able to implement using bubble sort, but I want a faster sorting method. Is there a way to sort my list using the sort() or sorted() (Using comparator or something similar) functions while pertaining to my condition ?


Solution

  • You can create a comparator function that retuns a tuple; tuples are compared from left to right until one of the elements is "larger" than the other. Your input/output example is quite lacking, but I believe this will result into what you want:

    def my_compare(x):
        return x[1][1], x[1][0]
    
    ans.sort(key=my_compare)
    # ans = sorted(ans, key=my_compare)
    

    Essentially this will first compare the x[1][1] value of both ans[j] and ans[j+1], and if it's the same then it will compare the x[1][0] value. You can rearrange and add more comparators as you wish if this didn't match your ues case perfectly.