python - 为什么这个浮点转换异常没有被很好地捕捉到?
问题描述
这样做Python 2.7.15
:
dirlist = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
for x in dirlist:
try:
float(x)
except (ValueError, TypeError):
dirlist.remove(x)
print dirlist
结果是:
['abgafhb', '100', '115.4', '125']
再次运行for
循环会清除'abgafhb'
.
我错过了什么?
PS尝试except
了没有参数,结果是一样的。
解决方案
您不应该修改您正在迭代的列表。也许将成功的值存储在一个新列表中。
dir_list = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
new_list = []
for x in dir_list:
try:
float(x)
new_list.append(x)
except (ValueError, TypeError):
pass
print dir_list # will not have changed
print new_list # will contain only strings that can be converted to float
推荐阅读
- javascript - 当嵌套对象的属性值更改时,Angular 7 [禁用] 未检测到更改
- java - Firebase onDataChange - 值事件侦听器不侦听更改
- go - cmd/go: go:binary-only-package 在 go 1.10 #24318 中不起作用
- signals - Godot - 任何跟踪信号的方法?
- php - 如何在内容创世纪主题后添加一段 HTML
- linux - for, do, done 在 linux 中将 txt 转换为 biom 格式
- python - Scrapy 组合来自多个进程的项目
- elasticsearch - Elasticsearch:强制合并降低性能
- javascript - 反应全局声明变量得到流类型错误
- sql - 选择多个值作为一列,而不是每个值的列,SQL Server