sorted 在python2和3中的區別
python3中取消了cmp參數
python3中的使用方法如下:
from functools import cmp_to_key
def my_cmp(i1, i2):
return 1 if i1 < i2 else -1
print(sorted([1, 2, 3], key=cmp_to_key(my_cmp)))
原理如下:
class K(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return 1
def __gt__(self, other):
return 1
def __eq__(self, other):
return 1
def __le__(self, other):
return 1
def __ge__(self, other):
return 1
__hash__ = None
print(sorted([1, 2, 3], key=K))