日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python3之字符串比較_重寫cmp函數(shù)方式_python

作者:solitary_w ? 更新時間: 2022-04-15 編程語言

Python3字符串比較_重寫cmp函數(shù)

由于在C ++中習(xí)慣了使用CMP函數(shù),所以在遇到字符串排序時,想當(dāng)然的去使用sort(開始,結(jié)束,CMP)去對列表進(jìn)行排序,但結(jié)果好像不行。

后來查閱網(wǎng)上資料,好像在python3中CMP函數(shù)已經(jīng)被取代了。

故而只能另求他法了。下面是很簡單的一個字符串日期提取及根據(jù)日期排序。

需求是這樣的,由于從文本中讀入的字符串是無序的,但在輸出時需要按時間前后輸出。

不多說,直接上代碼

#!/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)

以上為自定義排序的一個小小實現(xiàn),對于自定義排序,本小白主要用于對自定義結(jié)構(gòu)體的數(shù)組,字典等的排序,以后會用于更多地方。

字符串比較 cmp op.eq

python3 不再使用cmp(str1,str2)來比較字符串

被operator模塊代替,需要導(dǎo)入模塊。

直接使用cmp,會出現(xiàn)錯誤

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

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

python -V

python3 比較字符串如下

原文鏈接:https://blog.csdn.net/qq_38328875/article/details/83149341

欄目分類
最近更新