zoukankan      html  css  js  c++  java
  • python自定义排序

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

    Generally, you want to use the built-in sorted() 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 sorted before the right item
    • return a positive value (> 0) when the left item should be sorted after the right item
    • return 0 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:

    def compare(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 left item1 is bigger than the weight of the right item2. Hence item1 will be sorted after item2.

    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 import cmp_to_key
    sorted(mylist, key=cmp_to_key(compare))

    or

    from functools import cmp_to_key
    sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
  • 相关阅读:
    录制caf 转 mp3
    关于百度地图iOS中 paopaoView 警告的处理方法
    iphone JB开发小记(四)theos、iosOpenDev的调试
    USB 漏洞影响超100万来自不同供应商的路由器
    进程 线程 纤程 中断
    synchronized、ReentrantLock、volatile
    TimeUnit用法
    2021年vivo互联网技术最受欢迎文章TOP25
    前端质量提升利器马可代码覆盖率平台
    zyh@163.net
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13854636.html
Copyright © 2011-2022 走看看