Python3 list 自定义比较函数
如题,解决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 自定义比较函数相关推荐
- C++中自定义比较函数和重载运算符总结
sort 自定义比较函数 //示例 struct node{int x, y; };bool cmp(const node& a, const node& b){return a.x ...
- stl中各种容器的自定义比较函数
class elem { public:elem();elem(int aa):a(aa){} public:int a;int getA(){return a;} };class elem1 { p ...
- c++ 自定义比较函数,运行时发生segmentation fault
c++ map自定义比较函数,发生运行时越界. #include <string> #include <iostream> #include <list> #inc ...
- python3多线程自定义threading子类
python3多线程自定义threading子类 解决问题 代码实例 解决问题 1.python3多线程自定义threading.Thread的子类: 2.多线程并行,获取多线程运行结果 代码实例 i ...
- python自定义函数的关键字_Python3.x中自定义比较函数
在Python3.x的世界里,cmp函数没有了.那么sorted,min,max等需要比较函数作为参数的函数该如何用呢? 以min函数的定义为例,有两种重载形式: 单参数(一个迭代器): 复制代码 代 ...
- 关于set的自定义比较函数的使用及结构体的上下二分用法
如果set的类型是个结构体 我们需要定义重载函数 ***set 容器模版需要3个泛型参数,如下: template <class Key,class Compare = less <key ...
- python3 导入自定义函数
python中导入自定义函数是from .... import...... from 是你自定义的文件名(全路径名称)import是导入的函数名称(*表示导入所有的函数) 如果已经把my_abs()的 ...
- 优先队列priority_queue自定义比较函数
以一个例子进行说明,假设优先队列的每个元素是pair<int,int>,我需要自定义一个用于pair<int,int>比较的函数: decltype返回该变量的类型 bool ...
- Python3导入自定义模块的3种方式
关于如何自定义一个模块,如果大家不懂的话还请先看下面这篇博文 ↓ http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df4 ...
最新文章
- java url特殊字符处理_简单实例处理url特殊符号处理(2种方法)
- best,best,best ......何恺明开挂之路
- 魏伟:学习音视频技术要先理论再实现
- MarkDown语法-使用博客园的markDown编辑
- asp.net core 系列之Startup
- python不同数据的读入_python读写不同编码txt文件_python读写txt文件
- 手机端局部滚动问题 overflow-y:auto
- H5本地储存Web Storage
- OpenGL基础30:模板测试
- 平面设计常用标准尺寸
- camscanner(扫描全能王)功能解析与复现
- 一道逻辑题 房间里有100盏电灯
- defaultdic与dict对比
- (CRON) info (No MTA installed, discarding output
- 24年前他被余承东招入华为,现在掌舵第四大事业群,对垒阿里张建锋、百度王海峰,腾讯汤道生...
- 【python 库】 pandas 教程
- 如果格局决定人生,那到底什么决定了格局
- 2023年美国大学生数学建模竞赛(春季赛)
- 10大电子书免费下载网站
- springboot参数转换Json格式化问题