简体   繁体   中英

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

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.

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

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.

You can do this without any imports too

highest_number = 0
highest_element = ""

for item in list_data:
    parts = item.split('_')[2].split('.')
    number = float(parts[0]) + float(parts[1]) / (10 ** len(parts[1]))
    if number > highest_number:
        highest_number = number
        highest_element = item

print(highest_element)

>>> version_v_10.1.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM