天天看点

python自定义排序

发现不是很清楚,遂整理stackoverflow如下

generally, you want to use the built-in <code>sorted()</code> function which takes a custom comparator as its parameter.

we need to pay attention to the fact that in python 3 the parameter name and semantics have changed.

when providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):

return a negative value (<code>&lt; 0</code>) when the left item should be sorted before the right item

return a positive value (<code>&gt; 0</code>) when the left item should be sorted after the right item

return <code>0</code> when both the left and the right item have the same weight and should be ordered "equally" without precedence

in the particular case of the op's question, the following custom compare function can be used:

using the minus operation is a nifty trick because it yields to positive values when the weight of left <code>item1</code> is bigger than the weight of the right <code>item2</code>. hence <code>item1</code> will be sorted after <code>item2</code>.

if you want to reverse the sort order, simply reverse the subtraction: <code></code>

or