首页 > 解决方案 > Exception Handling in Loops in python

问题描述

I try to capture multiple IndexErrors in the same loop, yet I can only capture the first one. This question might be related to my question, yet I cannot understand it. If it helps, I am using Enthought Canopy 1.6.2 on Windows 10 and Python 2.7.13.

import numpy as np

some_array=np.zeros(10)
some_set=[2,4,15,19]
for sense in some_set:
    try:
        some_array[sense]=1
    except IndexError:
        some_set.remove(sense)
        print some_set, "sense"

The output I receive is:

[2, 4, 19] sense

While I want an output of the form

[2, 4, 19] sense

[2, 4] sense

标签: pythonpython-2.7exception

解决方案


您的问题来自您正在修改循环遍历的数组这一事实。在 pythonfor x in y:中 a 与for i in range(len(y)): x = y[i].

问题是您在循环中位于索引 2 处,这会产生 element 15。然后,您捕获错误并15从数组中删除。都好。但是,现在您正在循环的数组是[2, 4, 19]并且您刚刚结束了一次迭代,让 Python 知道索引 3 处的元素是什么。不再有索引 3,因此 Python 将终止循环。

要阻止您的问题发生,只需循环遍历数组的副本,这样您就不会更改正在检查的数组,使用.copy()or [:]

import numpy as np
some_array=np.zeros(10)
some_set=[2,4,15,19]
for sense in some_set[:]:  # This line was changed to use [:]
    try:
        some_array[sense]=1
    except IndexError:
        some_set.remove(sense)
        print some_set, "sense"

推荐阅读