Using a comparator function to sort

前端 未结 2 446
我寻月下人不归
我寻月下人不归 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.)

    0 讨论(0)
  • 2020-12-15 03:48

    In Python 3 there is no cmp argument for the sorted function (nor for list.sort).

    According to the docs, the signature is now sorted(iterable, *, key=None, reverse=False), so you have to use a key function to do a custom sort. The docs suggest:

    Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

    Here's an example:

    >>> def compare(x, y):
    ...     return x[0] - y[0]
    ... 
    >>> data = [(4, None), (3, None), (2, None), (1, None)]
    >>> from functools import cmp_to_key
    >>> sorted(data, key=cmp_to_key(compare))
    [(1, None), (2, None), (3, None), (4, None)]
    

    However, your function doesn't conform to the old cmp function protocol either, since it returns True or False. To convert cmpValue into the appropriate form, you can do:

    def predicate_to_cmp(predicate):
        def cmp(x, y):
            if predicate(x, y):
                return 1
            elif x == y:
                return 0
            else:
                return -1
        return cmp
    

    Then you can do:

    >>> your_key = cmp_to_key(predicate_to_cmp(cmpValue))
    >>> sorted(data, key=your_key)
    [(1, None), (2, None), (3, None), (4, None)]
    
    0 讨论(0)
提交回复
热议问题