如何在Python中修改生成器? [英] How do I modify a generator in Python?

查看:86
本文介绍了如何在Python中修改生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Take a look at the documentation for other examples, including things like ifilter, dropwhile and islice to name just a few more.

这篇关于如何在Python中修改生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆