这取决于是什么iter
。如果它是通过对可迭代对象的调用创建iter()
的迭代器,那么是的,调用next(iter)
也会推进迭代器:
>>> it = iter(range(4))
>>> for x in it:
print(x)
_ = next(it)
0
2
重要的是它it
是一个迭代器(而不是任何可迭代的),因为 for 循环也会iter()
在内部调用该对象。由于迭代器(通常)在iter(some_iterator)
被调用时会返回自己,所以这很好用。
这是个好主意吗?通常不会,因为它很容易损坏:
>>> it = iter(range(3))
>>> for x in it:
print(x)
_ = next(it)
0
2
Traceback (most recent call last):
File "<pyshell#21>", line 3, in <module>
_ = next(it)
StopIteration
您必须StopIteration
在循环内手动添加异常处理;这很容易变得一团糟。当然,您也可以使用默认值,例如next(it, None)
,但是这很快就会变得混乱,尤其是当您实际上没有将值用于任何事情时。
一旦有人后来决定在 for 循环中不使用迭代器而是使用其他可迭代的对象,整个概念也会中断(例如,因为他们正在重构代码以使用列表,然后一切都中断了)。
您应该尝试让 for 循环成为唯一使用迭代器的循环。更改您的逻辑,以便您可以轻松确定是否应跳过迭代:如果可以,请先过滤可迭代对象,然后再开始循环。否则,使用条件来跳过循环内的迭代(使用continue
):
>>> it = filter(lambda x: x % 2 == 0, range(3))
>>> for x in it:
print(x)
0
2
>>> it = range(3) # no need for an iterator here
>>> for x in it:
if x % 2 == 1:
continue
print(x)
0
2