在具有默认值的列表上使用iter

2024-04-24 02:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够做到这一点:

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

Tags: thedefaultobjectfooisbarvalbe
1条回答
网友
1楼 · 发布于 2024-04-24 02:47:01

python方法通常是使用for循环:

for val in foo:
    print(val)

或者,如果不起作用,则将默认值放在next调用中,而不是将其附加到迭代器本身:

bar = iter(foo)
val = next(bar, "default")

如果您真的想在迭代器中执行此操作,可以使用itertools.chain将迭代器与sentinel值的无限序列链接起来:

from itertools import chain, repeat
bar = chain(foo, repeat("default"))

要跳过for循环中的元素,可以:

bar = iter(foo)
for val in bar:
    if_some_condition():
        next(bar) # skips over the next iteration of the loop

相关问题 更多 >