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

后端 未结 4 544
[愿得一人]
[愿得一人] 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 13:47

    One way could be to create a reversor class and use it to decorate the key in question. This class could be used to reverse any field that is comparable.

    class reversor:
        def __init__(self, obj):
            self.obj = obj
    
        def __eq__(self, other):
            return other.obj == self.obj
    
        def __lt__(self, other):
            return other.obj < self.obj
    

    Use it like so:

    sortedList = sorted(myList, key=lambda(y): (y[0].lower(), reversor(y[1]))
    

提交回复
热议问题