How to find the highest floating number value in a given list of strings in Python?

Question:

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.

Asked By: tins johny

||

Answers:

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
Answered By: Bhargav

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.

Answered By: S.B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.