Using a comparator function to sort

前端 未结 2 448
我寻月下人不归
我寻月下人不归 2020-12-15 03:16

So I\'m working with a few pre-existing comparators that compare certain values in two tuples and return true if the first is greater than the second, false if otherwise. He

2条回答
  •  伪装坚强ぢ
    2020-12-15 03:43

    You're passing the comparator as the key function. You should be passing it as the cmp, wrapped in some kind of function that turns it into a proper comparator.

    def make_comparator(less_than):
        def compare(x, y):
            if less_than(x, y):
                return -1
            elif less_than(y, x):
                return 1
            else:
                return 0
        return compare
    
    sortedDict = sorted(subjects, cmp=make_comparator(cmpValue), reverse=True)
    

    (Although actually, you should be using key functions:

    sorted(subjects, operator.itemgetter(0), reverse=True)
    

    Also note that sortedDict will not actually be a dict, so the name is rather confusing.)

提交回复
热议问题