Skip to main content

代码优化

多层循环使用异常跳出

image-20220726214828063

  • 传统写法
found = False
for row, record in enumerate(table):
for column, field in enumerate(record):
for index, item in enumerate(field):
if item == target:
found = True
break
if found: break
if found: break
if found: break
  • 使用异常优化
class FoundException(Exception): pass

try:
for row, record in enumerate(table):
for column, field in enumerate(record):
for index, item in enumerate(field):
if item == target:
raise FoundException()
except FoundException:
# 查找成功
else:
# 查找失败