Python中是否可以使用一个通用接口来修改生成器的行为?
Is there a common interface in Python that I could derive from to modify behavior of a generator?
例如,我想修改一个现有的生成器,以便在流中插入一些值,并删除一些其他值.
For example, I want to modify an existing generator to insert some values in the stream and remove some other values.
我该怎么做?
感谢Boda Cydo
Thanks, Boda Cydo
推荐答案您可以使用 itertools 生成一个发电机并产生一个新的发电机.
You can use the functions provided by itertools to take a generator and produce a new generator.
例如,您可以使用 takewhile 直到谓词为no不再满足,并且链包含一系列新值.
For example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.
看看其他示例的文档,包括 ifilter , dropwhile 和 islice 仅举几例.
Take a look at the documentation for other examples, including things like ifilter, dropwhile and islice to name just a few more.
更多推荐
如何在Python中修改生成器?
发布评论