繁体   English   中英

Python:从字符串中提取多个浮点数

[英]Python: Extract multiple float numbers from string

原谅我,我是Python的新手。

给定一个以不确定长度的浮点开始并以相同长度结束的字符串,我如何将它们都提取到数组中,或者如果只有一个浮点,则只有一个。

例:

"38.00,SALE ,15.20"
"69.99"

我想退货:

[38.00, 15.20]
[69.99]

您也可以使用正则表达式执行此操作

import re
s = "38.00,SALE ,15.20"
p = re.compile(r'\d+\.\d+')  # Compile a pattern to capture float values
floats = [float(i) for i in p.findall(s)]  # Convert strings to float
print floats

输出:

[38.0, 15.2]
def extract_nums(text):
    for item in text.split(','):
        try:
            yield float(item)
        except ValueError:
            pass

print list(extract_nums("38.00,SALE ,15.20"))
print list(extract_nums("69.99"))

[38.0, 15.2]
[69.99]

但是,使用float转换会失去精度 ,如果要保持精度,可以使用decimal

import decimal

def extract_nums(text):
    for item in text.split(','):
        try:
            yield decimal.Decimal(item)
        except decimal.InvalidOperation:
            pass

print list(extract_nums("38.00,SALE ,15.20"))
print list(extract_nums("69.99"))

[Decimal('38.00'), Decimal('15.20')]
[Decimal('69.99')]

您说过,您只对字符串开头和结尾的浮点数感兴趣,因此假设它以逗号分隔:

items = the_string.split(',')
try:
    first = float(items[0])
except (ValueError, IndexError):
    pass
try:
    second = float(items[-1])
except (ValueError, IndexError):
    pass

我们必须将操作包装在异常处理程序中,因为该值可能不是有效的浮点数( ValueError )或list可能不存在索引( IndexError )。

这将处理所有情况,包括省略一个或两个浮点数的情况。

您可以尝试类似

the_string = "38.00,SALE ,15.20"
floats = []
for possible_float in the_string.split(','):
    try:
        floats.append (float (possible_float.strip())
    except:
        pass
print floats

尝试列表理解:

just_floats = [i for i in your_list.split(',') if i.count('.') == 1]

首先,您将字符串分割成逗号,然后过滤掉字符串并去除没有小数位的值

import re    
map(float, filter(lambda x: re.match("\s*\d+.?\d+\s*", x) , input.split(","))

输入: input = '38.00,SALE ,15.20'输出: [38.0, 15.2]

输入: input = '38.00,SALE ,15.20, 15, 34.' 输出: [38.0, 15.2, 15.0, 34.0]

说明:

  1. 想法是分割字符串: list_to_filter = input.split(",")分割,
  2. 然后使用正则表达式过滤器字符串,这些字符串是实数: filtered_list = filter(<lambda>, list_to_filter) ,如果lamda表达式为true,则此项目包含在过滤器的输出中。 因此,当re.match("\\s*\\d+.?\\d+\\s*", x)匹配字符串x filter会保留它。
  3. 最后转换为浮点数。 map(float, filtered_list) 它的作用是将float()函数应用于列表的每个元素

分割输入,删除句点时检查每个元素是否为数字,如果是则转换为float。

def to_float(input):
    return [float(x) for x in input.split(",") if unicode(x).replace(".", "").isdecimal()]

暂无
暂无

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

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