首页 > 解决方案 > 如何在不引发 ValueError 的情况下过滤可以从字符串转换为浮点数的元素列表?

问题描述

说我有以下列表

w = ['Elapsed', 'time:', '0', 'days', '8', 'hours', '22', 'minutes', '15.9', 'seconds.']

我想过滤这个列表,只返回可以转换为浮点数而不用 raise 的元素ValueError。我可以

l = []
for el in w:
    try:
        l.append(float(el))
    except ValueError:
        continue

但是我想知道是否有一种强大的方法可以使用filterandlambda函数在一行中实现相同的功能?或者perhpas还有另一种方式?

标签: python

解决方案


过滤方式

l = list(map(float, filter(lambda x: x.replace('.', '', 1).lstrip('+-').isdecimal(), w)))

列表理解方式

l = [float(x) for x in w if x.replace('.', '', 1).lstrip('+-').isdecimal()]

isfloat 函数

def isfloat(x: str) -> bool:
    x = x.replace('.', '', 1)    # strip first '.', so we can use isdecimal
    x = x.lstrip('+-')           # strip sign(prosible)
    return x.isdecimal()

str.isdigit、isnumeric 和 isdecimal 的区别


推荐阅读