如题,解决Python3中list自定义比较的问题。

1. 定义比较函数

def cmp(a, b):

2. 将其转换为键函数。下面的包装解决了这一问题:

def cmp_to_key(mycmp):class K:def __init__(self, obj, *args):self.obj = objdef __lt__(self, other):return mycmp(self.obj, other.obj) < 0def __gt__(self, other):return mycmp(self.obj, other.obj) > 0def __eq__(self, other):return mycmp(self.obj, other.obj) == 0def __le__(self, other):return mycmp(self.obj, other.obj) <= 0def __ge__(self, other):return mycmp(self.obj, other.obj) >= 0def __ne__(self, other):return mycmp(self.obj, other.obj) != 0return K

3. 调用比进行比较

li_sort = sorted(li, key=cmp_to_key(cmp), reverse=True)

Python3 list 自定义比较函数相关推荐

  1. C++中自定义比较函数和重载运算符总结

    sort 自定义比较函数 //示例 struct node{int x, y; };bool cmp(const node& a, const node& b){return a.x ...

  2. stl中各种容器的自定义比较函数

    class elem { public:elem();elem(int aa):a(aa){} public:int a;int getA(){return a;} };class elem1 { p ...

  3. c++ 自定义比较函数,运行时发生segmentation fault

    c++ map自定义比较函数,发生运行时越界. #include <string> #include <iostream> #include <list> #inc ...

  4. python3多线程自定义threading子类

    python3多线程自定义threading子类 解决问题 代码实例 解决问题 1.python3多线程自定义threading.Thread的子类: 2.多线程并行,获取多线程运行结果 代码实例 i ...

  5. python自定义函数的关键字_Python3.x中自定义比较函数

    在Python3.x的世界里,cmp函数没有了.那么sorted,min,max等需要比较函数作为参数的函数该如何用呢? 以min函数的定义为例,有两种重载形式: 单参数(一个迭代器): 复制代码 代 ...

  6. 关于set的自定义比较函数的使用及结构体的上下二分用法

    如果set的类型是个结构体 我们需要定义重载函数 ***set 容器模版需要3个泛型参数,如下: template <class Key,class Compare = less <key ...

  7. python3 导入自定义函数

    python中导入自定义函数是from .... import...... from 是你自定义的文件名(全路径名称)import是导入的函数名称(*表示导入所有的函数) 如果已经把my_abs()的 ...

  8. 优先队列priority_queue自定义比较函数

    以一个例子进行说明,假设优先队列的每个元素是pair<int,int>,我需要自定义一个用于pair<int,int>比较的函数: decltype返回该变量的类型 bool ...

  9. Python3导入自定义模块的3种方式

    关于如何自定义一个模块,如果大家不懂的话还请先看下面这篇博文 ↓ http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df4 ...

最新文章

  1. java url特殊字符处理_简单实例处理url特殊符号处理(2种方法)
  2. best,best,best ......何恺明开挂之路
  3. 魏伟:学习音视频技术要先理论再实现
  4. MarkDown语法-使用博客园的markDown编辑
  5. asp.net core 系列之Startup
  6. python不同数据的读入_python读写不同编码txt文件_python读写txt文件
  7. 手机端局部滚动问题 overflow-y:auto
  8. H5本地储存Web Storage
  9. OpenGL基础30:模板测试
  10. 平面设计常用标准尺寸
  11. camscanner(扫描全能王)功能解析与复现
  12. 一道逻辑题 房间里有100盏电灯
  13. defaultdic与dict对比
  14. (CRON) info (No MTA installed, discarding output
  15. 24年前他被余承东招入华为,现在掌舵第四大事业群,对垒阿里张建锋、百度王海峰,腾讯汤道生...
  16. 【python 库】 pandas 教程
  17. 如果格局决定人生,那到底什么决定了格局
  18. 2023年美国大学生数学建模竞赛(春季赛)
  19. 10大电子书免费下载网站
  20. springboot参数转换Json格式化问题

热门文章

  1. Groovy学习()面向Java开发者的Groovy
  2. Appium之创建、连接夜神模拟器
  3. 【Python】 文件目录比较工具filecmp和difflib
  4. P1284 三角形牧场
  5. Html5浏览器支持
  6. Know about Oracle RAC Heartbeat
  7. iBatis 配置文件详解
  8. python能解密java的,在python中解码Java对象
  9. 深入理解Semaphore
  10. php中隐藏网址,是否隐藏前台网址中的index.php文件名 解决方法