语法:
next(iterable[, default])
# iterable -- 可迭代对象
# default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。
例子:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
break
it = iter([1, 2, 5, 4, 3])
while True:
x = next(it, 'a')
print(x)
if x == 'a':
break
ps = [1,2,3,4,5]
x = iter(ps)
while True:
p = next(x)
if p.text == 3:
print(p.text)
break