查找许多文件中版本号最大的文件?

finding the largest version number file of of many files?

您好,我在一个文件夹中有 json 个文件的列表。

['user_sample_v001.json', 'user_sample_v002.json', 'user_sample_v105.json']

所以 pythonically 我正在尝试获取最新版本

>>> for item in lst:
...  print os.path.splitext(item.split("_")[-1])[0]

v001
v002
v105

给了我喜欢这个的数字列表:

>>> for version in versions:
...  number = ""
...  for num in version:
...   if num.isdigit():
...    number = "{0}{1}".format(number, num)
...  nums.append(number)
... 
>>> nums
['001', '002', '105']

然后我可以做 max(nums) 给我 '105'

然后我可以这样检查:

for user_sample in lst:
    if max_num in user_sample:
        print user_sample

这给了我 'user_sample_v105.json' 能否进一步优化准确性和性能?

您可以将 max() 函数与自定义 key= 函数一起使用:

import re

lst = ['user_sample_v001.json', 'user_sample_v002.json', 'user_sample_v105.json']

pattern = re.compile(r'_v(\d+)\.json')

m = max(lst, key=lambda k: int(pattern.search(k).group(1)))
print(m)

打印:

user_sample_v105.json