首页 > 解决方案 > 为什么这个浮点转换异常没有被很好地捕捉到?

问题描述

这样做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了没有参数,结果是一样的。

标签: python

解决方案


您不应该修改您正在迭代的列表。也许将成功的值存储在一个新列表中。

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

推荐阅读