python - 在列表中查找最新版本
问题描述
我可以通过文件夹搜索所有版本日志行,但我试图在列表中选择最新版本,但我不知道如何,因为列表的元素同时包含字符和数字。
下面是我的代码,用于查找和创建一个名为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)
在此列表中找到最新版本后,我希望将其与可能在文件夹之外的实际最新版本号进行比较。
解决方案
首先,您需要从字符串中捕获版本号并将其转换tuple
为int
. (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'
推荐阅读
- lyft-api - 使用 Lyft API 订购多趟行程?
- html - 字体系列不会更改 CSS h2 和 h3 标签,从谷歌字体导入
- excel - 用于 Excel 工作表的 Podio 项目
- r - R:将年度指标变量转换为单年变量
- javascript - 为什么 DOM 点击事件需要这么长时间?
- javascript - 角度路由/导航无法正常工作:附加而不是替换组件
- php - php date() 提前 1 天给出结果
- html - 输入 type="checkbox" 在 Outlook 上发送的 HTML Mailer 上损坏
- sql - Vertica:将 Bitstrint 转换为整数
- sql - Transform table using Cross Apply