时间:2022-12-10 12:10:39 | 栏目:Python代码 | 点击:次
由于在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)
以上为自定义排序的一个小小实现,对于自定义排序,本小白主要用于对自定义结构体的数组,字典等的排序,以后会用于更多地方。
python3 不再使用cmp(str1,str2)来比较字符串
被operator模块代替,需要导入模块。

如何查看自己的python版本,我的是windows
命令:(注意V一定要大写)
python -V
