如题,解决Python3中list自定义比较的问题。
1. 定义比较函数
def cmp(a, b):
2. 将其转换为键函数。下面的包装解决了这一问题:
def cmp_to_key(mycmp):
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
3. 调用比进行比较
li_sort = sorted(li, key=cmp_to_key(cmp), reverse=True)