[英]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.我想从列表中获取最高元素“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"
.您感兴趣的号码是正则表达式r"version_v_(.*).json"
的第一组。 You then need to split it to get a list of numbers and convert each number to int
.然后您需要拆分它以获得数字列表并将每个数字转换为int
。 At the end, you basically compare list of integers together like [8, 5]
, [8, 4]
, [10, 1]
.etc.最后,您基本上将整数列表一起比较[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.这样它就可以正确地找到比“ "version_v_10.10.json"
大的"version_v_10.2.json"
,因为它们是软件版本。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.