sort Python list with two keys but only one in reverse order

后端 未结 4 542
[愿得一人]
[愿得一人] 2020-11-28 13:40

I was wondering what would be a Pythonic way of sorting a list of tuples by two keys whereby sorting with one (and only one) key would be in a reverse order and sorting with

4条回答
  •  醉话见心
    2020-11-28 14:09

    Sometimes there is little alternative but to use a comparator function. There was a cmp argument to sorted from its introduction to 2.4, but it was removed from Python 3 in favour of the more efficient key function. In 3.2, cmp_to_key was added to functools; it creates keys from the original objects by wrapping them in an object whose comparison function is based on the cmp function. (You can see a simple definition of cmp_to_key at the end of the Sorting How-To

    In your case, since lower-casing is relatively expensive, you might want to do a combination:

    class case_insensitive_and_2nd_reversed:
        def __init__(self, obj, *args):
            self.first = obj[0].lower()
            self.second = obj[1]
        def __lt__(self, other):
            return self.first < other.first or self.first == other.first and other.second < self.second
        def __lt__(self, other):
            return self.first < other.first or self.first == other.first and other.second < self.second
        def __gt__(self, other):
            return self.first > other.first or self.first == other.first and other.second > self.second
        def __le__(self, other):
            return self.first < other.first or self.first == other.first and other.second <= self.second
        def __ge__(self, other):
            return self.first > other.first or self.first == other.first and other.second >= self.second
        def __eq__(self, other):
            return self.first == other.first and self.second == other.second
        def __ne__(self, other):
            return self.first != other.first and self.second != other.second
    
    sortedList = sorted(myList, key = case_insensitive_and_2nd_reversed)
    

提交回复
热议问题