在列表中查找最新版本 [英] Finding the latest version in a list
问题描述
我能够在文件夹中搜索所有版本日志行,但是我试图选择列表中的最新版本,但是我不知道怎么做,因为列表中的元素同时包含字符和数字.
I'm able to search through a folder to all the version log lines, but I am trying to select the newest version in the list, but I don't know how because the elements of the list contains both characters and numbers.
下面是我的代码,用于查找和创建一个名为matched_lines的列表,其中包含说明日志版本号的所有行.我希望从创建的此列表中找到最新版本,并将此最新版本与日志外部的实际最新版本进行比较.例如,生成的列表将包含:
Below is my code for find and creating a list called matched_lines that contains all the lines that states the version number of the log. I hope to find the newest version from this list created, and compare this newest version with the actual latest version outside of the log. For example, a generated list would consist:
['版本2.13.1.1','版本2.12.1.0','版本2.10.1.4']
['Version 2.13.1.1', 'Version 2.12.1.0', 'Version 2.10.1.4']
在此示例中,我希望选择版本2.13.1.1",并将其与日志的最新版本号进行比较,例如版本2.14.1.0".
In this example, I would hope to select "Version 2.13.1.1", and compare this with the latest version number the log, for example, "Version 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)
在此列表中找到最新版本后,我希望将其与文件夹之外的实际最新版本号进行比较.
After finding the newest version in this list, I hope to then compare it with the actual latest version number that may be outside of the folder.
推荐答案
首先,您需要从字符串中捕获版本号,并将其转换为 int
的 tuple
格式为(主要,次要,微型)
.将其用作 max
函数的 key
将返回最新版本.
First you need to capture the version number from the string and turn it into a tuple
of int
of the form (major, minor, micro)
. Using this as key
for the max
function will return the latest version.
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'
这篇关于在列表中查找最新版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!