简体   繁体   English

如何在处理生成器时处理StopIteration异常

[英]How to handle a StopIteration exception while dealing with generator

I'm working with a generator and I have the code below. 我正在使用生成器,我有下面的代码。 I'm a little confused about its logic. 我对它的逻辑有点困惑。

The generator in the function works fine as long as there is a 'False' at the end. 只要最后有一个'False',函数中的生成器就可以正常工作。 Removing it causes a StopIteration exception when running the function. 在运行该函数时,删除它会导致StopIteration异常。

Can anybody explain me the role of False here? 任何人都可以在这里向我解释False的作用吗?

>>> def some(coll, pred= lambda x:x)
...    return next((True for item in coll if pred(item)),False)
... 
>>> some([0,'',False])
False
>>> def some(coll, pred= lambda x:x):
...     return next((True for item in coll if pred(item)))
...
>>> some([0,'',False])
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    some([0,'',False])
  File "<pyshell#63>", line 2, in some
    return next((True for item in coll if pred(item)))
StopIteration

You are passing in a default value for the next() function to return if the generator expression raises a StopIteration exception. 如果生成器表达式引发StopIteration异常,则传入next()函数的默认值。 The False is the default value returned here: False是此处返回的默认值:

Retrieve the next item from the iterator by calling its __next__() method. 通过调用__next__()方法从迭代器中检索下一个项。 If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. 如果给定default ,则在迭代器耗尽时返回,否则引发StopIteration

Raising StopIteration is how iterators communicate that they are done and can no longer be used to produce results. 提高StopIteration是迭代器如何进行通信,它们已完成并且不能再用于生成结果。 Generators are a specialised type of iterator. 生成器是一种特殊类型的迭代器。

You don't have to pass in False ; 你不必传入False ; any valid Python value will do. 任何有效的Python值都可以。 If you omit the default argument, you can also omit the generator parenthesis: 如果省略默认参数,则还可以省略生成器括号:

next(True for item in coll if pred(item))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM