<p>根据官方文件-<a href="https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter" rel="nofollow noreferrer">https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter</a></p>
<blockquote>
<p>When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do:</p>
</blockquote>
<pre><code>def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
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
</code></pre>
<blockquote>
<p>To convert to a key function, just wrap the old comparison function:</p>
</blockquote>
^{pr2}$