I have a list of data which contains some alphanumeric contents.
list_data = ['version_v_8.5.json', 'version_v_8.4.json', 'version_v_10.1.json']
i want to get the highest element which is "version_v_10.1.json" from the list.
CodePudding user response:
sort using natsort then get last elemnt(which is highest version)
from natsort import natsorted
list_data = ['version_v_8.5.json', 'version_v_8.4.json', 'version_v_10.1.json']
list_data = natsorted(list_data)
print(list_data.pop())
outputs #
version_v_10.1.json
CodePudding user response:
You can do the following:
import re
list_data = [
"version_v_8.5.json",
"version_v_8.4.json",
"version_v_10.1.json",
"version_v_10.2.json", ####
"version_v_10.10.json", ####
]
pat = re.compile(r"version_v_(.*).json")
print(max(list_data, key=lambda x: [int(i) for i in pat.match(x).group(1).split(".")]))
Your interested number is the first group of the regex r"version_v_(.*).json"
. You then need to split it to get a list of numbers and convert each number to int
. At the end, you basically compare list of integers together like [8, 5]
, [8, 4]
, [10, 1]
.etc.
This way it correctly finds "version_v_10.10.json"
larger than "version_v_10.2.json"
as they are software versions.