1

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.

tins johny
  • 195
  • 1
  • 13

2 Answers2

3

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
1

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.

S.B
  • 13,077
  • 10
  • 22
  • 49
  • 1
    I'd recommend this answer because it uses the stdlib – SimonT Dec 22 '22 at 21:00
  • @SimonT Some less known 3rd-party libraries do an awesome job from time to time but it really depends on the task you're dealing with. For simple tasks, I definately use builtin tools. No need create too much extra dependencies and make the project bigger for nothing. Dependencies always come with costs...Do they constantly update the package? and etc. – S.B Dec 22 '22 at 21:06
  • 1
    I always try to use stdlib if I can mainly due to their efficiency and optimisation, especially re.compile in this case. But yes you are highly correct in that it does depend on use case. Especially when you don't want to rely on dependencies as a package etc. – SimonT Dec 22 '22 at 21:08
  • 1
    I guess that's just Stackoverflow users for you :( – SimonT Dec 22 '22 at 21:23