Python3之字符串比较_重写cmp函数方式

Bambi ·
更新时间:2024-05-17
· 1579 次阅读

目录

Python3字符串比较_重写cmp函数

不多说,直接上代码

字符串比较 cmp op.eq

直接使用cmp,会出现错误

python3 比较字符串如下

Python3字符串比较_重写cmp函数

由于在C ++中习惯了使用CMP函数,所以在遇到字符串排序时,想当然的去使用sort(开始,结束,CMP)去对列表进行排序,但结果好像不行。

后来查阅网上资料,好像在python3中CMP函数已经被取代了。

故而只能另求他法了。下面是很简单的一个字符串日期提取及根据日期排序。

需求是这样的,由于从文本中读入的字符串是无序的,但在输出时需要按时间前后输出。

不多说,直接上代码 #!/usr/bin/python #_*_coding:utf-8_*_ import functools import re def cmp(str1,str2): day1 = (re.search(r'\d{4}_\d{2}_\d{2}', str1)).group() day2 = (re.search(r'\d{4}_\d{2}_\d{2}', str2)).group() start1 = (re.search(r'Start\d', str1)).group() start2 = (re.search(r'Start\d', str2)).group() if day1 > day2: return 1 elif day1 < day2: return -1 elif start1 > start2: return 1 elif start1 < start2: return -1 else: return 0 if __name__ == '__main__': strList = [r"STRLIST2018_07_30\Start0", r"STRLIST2018_05_01\Start0", r"STRLIST2018_06_30\Start1", r"STRLIST2018_05_01\Start1", r"STRLIST2018_05_30\Start0", r"STRLIST2018_06_01\Start0", r"STRLIST2018_06_30\Start0", r"STRLIST2018_05_30\Start1", r"STRLIST2018_07_30\Start1", r"STRLIST2018_06_01\Start1" ] print("Is not sorted--------------") for i in strList: print(i) strList = sorted(strList,key = functools.cmp_to_key(cmp)) print("Has sorted-----------------") for i in strList: print(i)

以上为自定义排序的一个小小实现,对于自定义排序,本小白主要用于对自定义结构体的数组,字典等的排序,以后会用于更多地方。

字符串比较 cmp op.eq

python3 不再使用cmp(str1,str2)来比较字符串

被operator模块代替,需要导入模块。

直接使用cmp,会出现错误

如何查看自己的python版本,我的是windows

命令:(注意V一定要大写)

python -V

python3 比较字符串如下

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



字符串比较 cmp 字符串 Python3 Python 字符

需要 登录 后方可回复, 如果你还没有账号请 注册新账号