擅长:python、mysql、java
<p>要使用<a href="https://docs.python.org/3/howto/sorting.html" rel="nofollow">the new ^{<cd1>} argument</a>,只需将比较分解为已实现有序比较的另一个对象,例如元组或列表(例如整数序列)。这些类型之所以工作良好,是因为它们是按顺序排列的。在</p>
<pre><code>def ip_as_components (ip):
return map(int, ip.split('.'))
sorted_ips = sorted(ips, key=ip_as_components)
</code></pre>
<p><em>每个组件的顺序与传统比较然后按函数比较的单个测试相同。</em></p>
<p>看看火腿的点菜,你会发现:</p>
^{pr2}$
<p><code>key</code>方法(与其他语言中的“order by”类似)通常是一个更简单、更自然的构造来处理-假设原始类型是<em>而不是</em>已经很好地排序了。这种方法的主要缺点是部分反转(例如asc-then-desc)排序可能很棘手,但这可以通过返回嵌套元组等来解决</p>
<blockquote>
<p>In Py3.0, <em>the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language</em>, eliminating the conflict between rich comparisons and the <code>__cmp__()</code> magic method).</p>
</blockquote>
<p>如果绝对需要带有自定义“cmp”的<code>sorted</code>,则可以简单地使用<a href="https://docs.python.org/3/library/functools.html#functools.cmp_to_key" rel="nofollow">^{<cd4>}</a>。在</p>
<pre><code>sorted_ips = sorted(ips, key=functools.cmp_to_key(ip_compare))
</code></pre>