我希望能够做到这一点:
foo = ['a', 'b']
bar = iter(foo, "default")
val = next(bar)
while val !== "default":
print(val)
val = next(bar)
但是,这不起作用,因为在创建iter对象时有第二个参数。我从文档中看到,这改变了第一个值的使用方式:
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the
__iter__() method
), or it must support the sequence protocol (the__getitem__() method
with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its__next__() method
; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
但是我不认为有一种pythonic的方法可以不借助try/catch
(又称this)来做我想做的事情
bar = iter(foo)
try:
while True:
print(next(bar))
except StopIteration:
pass
python方法通常是使用for循环:
或者,如果不起作用,则将默认值放在
next
调用中,而不是将其附加到迭代器本身:如果您真的想在迭代器中执行此操作,可以使用
itertools.chain
将迭代器与sentinel值的无限序列链接起来:要跳过for循环中的元素,可以:
相关问题 更多 >
编程相关推荐