Python中有什么方法可以在迭代器/生成器抛出异常后继续迭代?像下面的代码一样,有没有办法跳过ZeroDivisionError并继续循环gener()而不使用modyfyingrun()函数?
gener()
run()
def gener(): a = [1,2,3,4,0, 5, 6,7, 8, 0, 9] for i in a: yield 2/i def run(): for i in gener(): print i #---- run script ----# try: run() except ZeroDivisionError: print 'what magick should i put here?'
逻辑上的位置try/except将是进行违规计算的位置:
try/except
def gener(): a = [1,2,3,4,0, 5, 6,7, 8, 0, 9] for i in a: try: yield 2/i except ZeroDivisionError: pass