为什么无法很好地捕获此float转换异常?

时间:2018-10-19 11:11:33

标签: 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'

我想念什么?

P.S。尝试except,不带参数,结果是相同的。

2 个答案:

答案 0 :(得分:2)

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

"scripts": {
  ...
  "debug": "npm run build && functions deploy api --trigger-http --timeout 600s && functions inspect api --port 9229"` 
}

答案 1 :(得分:1)

当您修改要遍历的列表时,Python不喜欢它,因为那样一来,它就不知道到达何处并感到困惑。

解决此问题的最简单(但不是最有效)的方法是遍历列表的副本:

dirlist = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125']
for x in dirlist[:]:  # Note the [:]
    try:
        float(x)
    except (ValueError, TypeError):
        dirlist.remove(x)
print dirlist
相关问题