python - 如何在不引发 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
但是我想知道是否有一种强大的方法可以使用filter
andlambda
函数在一行中实现相同的功能?或者perhpas还有另一种方式?
解决方案
过滤方式
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()
推荐阅读
- python - 从非连续视频帧创建全景图
- python - for 循环中的返回函数仅返回 1 项
- linux - 如何将目录及其子目录中的所有 PDF 文件复制到一个位置?
- macos - 在 Mac 上安装 ffmpeg 失败
- c++ - 我们如何在 C++ 中的无序映射中分配变量并更新它们?
- javascript - 为什么 JavaScript 没有检测到所有 cookie?
- java - 如何使用 Apache Tomcat 服务器在 VScode IDE 中设置 servlet 和 jsp 项目?
- javascript - 如何在方法单击时更新 sessionStorage 中的值?
- javascript - 如何在 String 对象的原型上实现这个测试?
- bash - bash脚本中的列表积累