首页 > 解决方案 > 在列表中查找最新版本

问题描述

我可以通过文件夹搜索所有版本日志行,但我试图在列表中选择最新版本,但我不知道如何,因为列表的元素同时包含字符和数字。

下面是我的代码,用于查找和创建一个名为matched_lines 的列表,其中包含说明日志版本号的所有行。我希望从创建的这个列表中找到最新版本,并将这个最新版本与日志之外的实际最新版本进行比较。例如,生成的列表将包括:

['版本 2.13.1.1'、'版本 2.12.1.0'、'版本 2.10.1.4']

在本例中,我希望选择“2.13.1.1 版本”,并将其与日志中的最新版本号进行比较,例如“2.14.1.0 版本”。

    for filename in files:

            #print('start parsing... ' + str(datetime.datetime.now()))
            matched_line = []
            try:
                with open(filename, 'r', encoding = 'utf-8') as f:
                    f = f.readlines()
            except:
                with open(filename, 'r') as f:
                    f = f.readlines()                 

            # print('Finished parsing... ' + str(datetime.datetime.now()))

            for line in f:
                #0strip out \x00 from read content, in case it's encoded differently
                line = line.replace('\x00', '')

                #regular expressions to fidn the version log lines for each type
                RE1 = r'^Version \d.\d+.\d.\d' #Sample regular expression

                pattern2 = re.compile('('+RE1+')', re.IGNORECASE)

                #for loop that matches all the available version log lines
                for match2 in pattern2.finditer(line):
                    matched_line.append(line)

在此列表中找到最新版本后,我希望将其与可能在文件夹之外的实际最新版本号进行比较。

标签: pythonpython-3.xdata-structuresversion

解决方案


首先,您需要从字符串中捕获版本号并将其转换tupleint. (major, minor, micro)使用 this 作为key函数max将返回最新版本。

代码

import re

def major_minor_micro(version):
    major, minor, micro = re.search('(\d+)\.(\d+)\.(\d+)', version).groups()

    return int(major), int(minor), int(micro)

例子

versions = ['Version 2.13.1.1', 'Version 2.12.1.0', 'Version 2.10.1.4']
latest = max(versions, key=major_minor_micro)

print(latest) # 'Version 2.13.1.1'

推荐阅读