python:从 python 字符串列表中提取浮点数(31.99 澳元)

python: extract float from a python list of string( AUD 31.99)

python:从 python 字符串列表中提取浮点数(31.99 澳元)。 我使用 openpyxl 从 excel 文件中读取数量列表。我将它保存在一个列表中,但该列表是这样的字符串形式:

['31.40 AUD', ' 32.99 AUD', '37.24 AUD']

我需要从字符串项列表中获取浮点数,以便稍后可以将其保存在新列表中以获取它们的总数。

期望的输出:

[31.40, 32.99, 37.24]

我已经尝试过这些:

newList = re.findall("\d+\.\d+", tot[0])
print(newList)

输出:

[31.40]

但是如何将它用于所有项目元素?

我是 python 的新手,这只是我做的一些工作,想使用 python 查看总数,而不是使用 excel 的查找和替换选项。 谢谢

是否可以改用字符串拆分?我觉得会简单很多

ls1 = ['32.46 AUD', '17.34 AUD']

myFloats = []
for aString in ls1:
    aFloat = float(aString.split()[0])
    myFloats.append(aFloat)

您可以使用map函数:

inList = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
output = list(map(lambda elem: float(elem.split()[0]), inList))
print(output)

输出:

[31.4, 32.99, 37.24]

如果您想使用正则表达式获取值列表,请尝试

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(re.search('\d+\.\d+', fl).group(0)) for fl in tot]
print(newList)
# [31.40, 32.99, 37.24]

但在这种情况下使用 split 似乎更容易解决

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.split()[0]) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

如果第二个子字符串总是相同的 ("AUD") 你也可以试试

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.rstrip(' AUD')) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

您应该考虑处理错误。例如,这是一种方法:

import re
import math

def float_from_string(str_):
    # Try to extract a floating number, if fail return nan
    r = re.search('\d+\.\d+', str_)
    return float(r.group()) if r else math.nan

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD', ' nonumberhere AUD']
totfloat = [float_from_string(i) for i in tot]

print(totfloat)

Returns:

[31.4, 32.99, 37.24, nan]