Python3字符串比较_重写cmp函数
由于在C ++中习惯了使用CMP函数,所以在遇到字符串排序时,想当然的去使用sort(开始,结束,CMP)去对列表进行排序,但结果好像不行。
后来查阅网上资料,好像在python3中CMP函数已经被取代了。
故而只能另求他法了。下面是很简单的一个字符串日期提取及根据日期排序。
需求是这样的,由于从文本中读入的字符串是无序的,但在输出时需要按时间前后输出。
不多说,直接上代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#!/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 'Startd' , str1)).group() start2 = (re.search(r 'Startd' , 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_30Start0" , r "STRLIST2018_05_01Start0" , r "STRLIST2018_06_30Start1" , r "STRLIST2018_05_01Start1" , r "STRLIST2018_05_30Start0" , r "STRLIST2018_06_01Start0" , r "STRLIST2018_06_30Start0" , r "STRLIST2018_05_30Start1" , r "STRLIST2018_07_30Start1" , r "STRLIST2018_06_01Start1" ] 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 比较字符串如下
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_38328875/article/details/83149341