繁体   English   中英

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 的查找和替换选项的总数。 谢谢

您可以使用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]

是否可以使用字符串拆分来代替? 我认为这会简单得多

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

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

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

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)

返回:

[31.4, 32.99, 37.24, nan]

考虑到列表如下

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

有多种方法可以提取浮点数。 下面将留下五个可能的选项。


选项1

将正则表达式与 Python 的re使用列表理解如下

import re

regex = re.compile(r'(\d+\.\d+)')
l = [float(regex.search(x).group(1)) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

选项 2

使用str.stripstr.split如下

l = [float(x.strip().split(' ')[0]) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

选项 3

使用str.split如下

l = [float(x.split()[0]) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

选项 4

一种方法是使用str.strip删除空格和货币( AUD ),如下所示

l = [float(x.strip(' AUD')) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

假设一个人有一个包含各种货币的列表(比如AUDUSDEUR ),因为一个人的列表只有AUD ,可以使用str.strip如下

hl = [' AUD', ' USD', ' EUR']

l = [float(x.strip(hl[0])) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

选项 5

适用于此用例的另一种方法如下

l = [float(x[:6]) for x in l]

[Out]: 

[31.4, 32.99, 37.24]

但是请注意,可能需要调整数字或采用不同的方法,具体取决于列表中字符串中的浮点数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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