python next()迭代器完成会引发StopIteration异常

li=[1,2,3,4]
it=iter(li)

print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it)) next()完成后引发StopIteration异常
---------------------------------------------------------
for l in it: #for循环自带异常处理 
    print(l)
---------------------------------------------------------
import sys  #while循环需要带异常处理
while True:
    try:
        print(next(it))
    except StopIteration:
        sys.exit()

你可能感兴趣的:(python)