100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python自定义排序规则_python自定义排序

python自定义排序规则_python自定义排序

时间:2022-07-17 09:28:18

相关推荐

python自定义排序规则_python自定义排序

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

Generally, you want to use the built-insorted()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.

How the custom comparator works

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 (< 0) when the left item should be sortedbeforethe right item

return a positive value (> 0) when the left item should be sortedafterthe right item

return0when 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:

defcompare(item1, item2):return fitness(item1) - fitness(item2)

Using the minus operation is a nifty trick because it yields to positive values when the weight of leftitem1is bigger than the weight of the rightitem2. Henceitem1will be sortedafteritem2.

If you want to reverse the sort order, simply reverse the subtraction:

return fitness(item2) - fitness(item1)

Calling sorted() in Python 2

sorted(mylist, cmp=compare)

or

sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))

Calling sorted() in Python 3

from functools importcmp_to_key

sorted(mylist, key=cmp_to_key(compare))

or

from functools importcmp_to_key

sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。