Python3版本號比較代碼實現


一、版本號比較的困難

不能直接以字符串形式進行比較:對於1.3和1.4直接以字符串進行比較是可以正確得出1.4比1.3大;但如果是1.3和1.14還直接進字符串比較那就是1.3比1.14大那就不對了。

不能直用用數值類型進行比較:如果版本號是1和2那可以自接以整型進行比較,如果是1.3和1.4可以直接以浮點型進行比較;但如果是1.3.1和1.4.1這種形式,那整型和浮點型都不能用了。

 

二、版本號比較實現思路

最關鍵的點就是每次取一節版本號、轉換成整型進行比較;比如1.2.3和1.2.14,先比較1,再比較2,最后再比較3得14。

 

三、實現

3.1 實現效果

 

3.2 實現代碼

compare_version----遞歸實現版本比較

pick_up_latest_version----調用compare_version,打印最終的版本比較結果

# version1----第一個要比較的版本字符串
# version2----第二個要比較的版本字符串
# split_flag----版本分隔符,默認為".",可自定義
# 返回值----相等返回0,version1比version2大返回1,version2比version1大返回2
# 接受的版本字符形式----空/x/x.y/x.y./x.y.z;兩個參數可為前邊列出的形式的任一種
def compare_version(version1=None,version2=None,split_flag="."):
    # 如果存在有為空的情況則進入
    if (version1 is None) or (version1 == "") or (version2 is None) or (version2 == ""):
        # version1為空且version2不為空,則返回version2大
        if ((version1 is None) or (version1 == "")) and (version2 is not None) and (version2 != ""):
            return 2
        # version2為空且version1不為空,則返回version1大
        if ((version2 is None) or (version2 == "")) and (version1 is not None) and (version1 != ""):
            return 1

    # 如果版本字符串相等,那么直接返回相等,這句會且只會在第一次比較時才可能進入
    # version1和version2都為空時也會進入這里
    if version1 == version2:
        return 0

    # 對版本字符串從左向右查找".",第一個"."之前的字符串即為此次要比較的版本
    # 如1.3.5中的1
    try:
        current_section_version1 = version1[:version1.index(split_flag)]
    except:
        current_section_version1 = version1
    try:
        current_section_version2 = version2[:version2.index(split_flag)]
    except:
        current_section_version2 = version2
    # 對本次要比較的版本字符轉成整型進行比較
    if int(current_section_version1) > int(current_section_version2):
        return 1
    elif int(current_section_version1) < int(current_section_version2):
        return 2

    # 如果本次傳來版本字符串中已沒有版本號分隔符,那說明本次比較的版本號已是最后一位版本號,下次比較值賦空
    # 如本次傳來的是5,那下次要比較的只能賦空
    try:
        other_section_version1 = version1[version1.index(split_flag)+1:]
    except:
        other_section_version1 = ""
    try:
        other_section_version2 = version2[version2.index(split_flag) + 1:]
    except:
        other_section_version2 = ""

    # 遞歸調用比較
    return compare_version(other_section_version1,other_section_version2)

# 此函數調用compare_version(),打印比較結果
def pick_up_latest_version(version1,version2):
    flag = compare_version(version1,version2)
    if flag == 0:
        print(f"version1 = {version1}, version2 = {version2}, the two version is equal")
    elif flag == 1:
        print(f"version1 = {version1}, version2 = {version2}, the latest version is version1 {version1}")
    elif flag == 2:
        print(f"version1 = {version1}, version2 = {version2}, the latest version is version2 {version2}")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM