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

Can I pass variables to the compare function in sorted method in Python?

Here is the code:

    if(order=="dsc"):
        return sorted(qs, key=compare_function, reverse=True)
    elif (order=="asc"): # asc
        # return sorted(qs, key=lambda obj: obj.teacher.name)
        return sorted(qs, key=compare_function)
    else:
        pass



def compare_function(obj):

    if obj == None:     
        return "aaaaaaa"
    if obj.teacher == None: 
        return "aaaaaaa"
    else:   
        test = {"teacher": obj.teacher}
        return test.get("teacher").name.lower()
    

What I expect is to pass some additional params to compare_function like below:

    if(order=="dsc"):
        return sorted(qs, key=compare_function(cls_name), reverse=True)
    elif (order=="asc"): # asc
        # return sorted(qs, key=lambda obj: obj.teacher.name)
        return sorted(qs, key=compare_function(cls_name))
    else:
        pass

    def compare_function(obj, cls_name):
        if obj == None:     
            return "aaaaaaa"
        if obj.teacher == None: 
            return "aaaaaaa"
        else:   
            test = {"teacher": obj.teacher}
            return test.get("teacher").name.lower()
    

But as I did this, no param was passed to compare_function. So the "obj" in compare_func will be None.

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

Then I tried to changed to

return sorted(qs, key=compare_function(obj, cls_name), reverse=True)

However, the interpretor complained the obj can’t be found this time.

How can I do?

Thanks.:)

p.s. I’m seeking for a general solution. :’)

>Solution :

You can pass a lambda as the key that invokes compare_function with an extra argument:

key=lambda x: compare_function(x, cls_name)
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