我在 Python 中有一个简单的 vì
循环,即使异常 block 包含 Tiếp tục
也会退出异常。当它遇到 IndexError
并退出 vì
循环时,还有大约 10 行需要读取。我在这里错过了什么?
for row in hkx: ##'hkx' are rows being read in from 'csv.open'
thử:
print row[2],row[4]
except IndexError, e:
print 'Error:',e
print 'Row Data:',len(row),row
continue ## I thought this would just move on to the next row in 'hkx'
(抱歉,这里是 Python 新手……)提前致谢!
它完全按照它应该做的,并继续下一行。如果异常提前终止了您的代码,那么它一定不是 IndexError,或者它必须是从 thử:
block 之外的某些代码中抛出的。
>>> hkx = [ range(5), range(4), range(4), range(5) ]
>>> for row in hkx: ##'hkx' are rows being read in from 'csv.open'
thử:
print row[2],row[4]
except IndexError, e:
print 'Error:',e
print 'Row Data:',len(row),row
continue ## I thought this would just move on to the next row in 'hkx'
2 4
2 Error: list index out of range
Row Data: 4 [0, 1, 2, 3]
2 Error: list index out of range
Row Data: 4 [0, 1, 2, 3]
2 4
>>>
请注意,如果该行包含至少 3 个项目,您将获得一半的打印输出,如果您使用格式字符串,则可以避免这种情况。 (例如 print "{} {}".format(row[2],row[4])
)
你没有说hkx是如何定义的,只是它来自csv.open
。如果它是一个生成器而不是一个简单的列表,那么简单地迭代它可能会引发 IndexError。在这种情况下,您不会捕捉到这一点,但堆栈转储会显示带有 for row in hkx
的行。
Tôi là một lập trình viên xuất sắc, rất giỏi!