是否可以在异常内部更改循环的计数器?
我尝试了一些不同的语法。它确实在异常中起作用,但是当循环再次执行时,更改似乎没有被应用。
for b in range(6, len(attribute_column)):
try:
print(b)
print(attribute_column[b])
qu = """ALTER TABLE products ADD %s NVARCHAR(200)""" % (attribute_column[b])
mycursor.execute(qu)
#if there is a multivalued column in json, POP the value and save it for another insertion
except mysql.connector.errors.ProgrammingError:
print(b)
attribute_column.pop(b)
redundant_values[attribute_column[b]] = attribute_value.pop(b)
b = b-1
print(b)
输出是这样的:
6
7
8
9
9
8
10
11
12
13
14
15
我需要这样:
6
7
8
9
9
8
9
10
11
12
13
14
15
答案 0 :(得分:0)
不能判断您的整体方法,但是总的来说,如果需要在计数器中进行任意状态更改,则可以编写自定义迭代器:
class Cursor:
def __init__(self, start, end):
self.end = end
self.position = start
def __next__(self):
if self.position >= self.end:
raise StopIteration
else:
self.position += 1
return self.position - 1
def __iter__(self):
return self
def revert(self, n=1):
self.position -= n + 1
示例:
if __name__ == '__main__':
cursor = Cursor(6, 16)
it = iter(range(3, -20, -1)) # for demo
for i in cursor:
print(i)
try:
i / next(it)
except ZeroDivisionError:
print("Error on:", i)
cursor.revert(1)
输出:
6
7
8
9
Error on: 9
8
9
10
11
12
13
14
15
Process finished with exit code 0