python - 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
解决方案
您的问题来自您正在修改循环遍历的数组这一事实。在 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"
推荐阅读
- java - Spring JPA findByEmail 不适用于 @ManyToMany 列连接
- c++ - 具有取消引用的模板 ReadProcessMemory
- authentication - Aleph 无法通过 SWI-Prolog 获得正确的理论
- javascript - 在 JavaScript 中发送简单的 TCP 消息,类似于 Python .socket
- javascript - 在 Web 应用程序的根级别安装 npm 和包
- python - Pandas:透视一个类型化的数据集
- python - 动态数组和删除运算符的 boost::python 内存错误
- javascript - 认证后渲染组件时反应页面闪烁
- spring - @Value 不提供来自应用程序属性 Spring Boot 的值
- hibernate - 需要帮助追踪 JPASystemException 的原因