finding the largest version number file of of many files?

Viewed 70

Hi I have list of json files in a folder.

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

so pythonically I am trying to get the latest version

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

v001
v002
v105

gives me list of numebrs liks this:

>>> 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']

then I can do max(nums) gives me '105'

then I can check like this:

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

that gives me 'user_sample_v105.json' can it be further more optimized for accuracy and performance ?

1 Answers

You can use max() function with custom key= function:

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)

Prints:

user_sample_v105.json
Related