简体   繁体   中英

How do I modify a generator in 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.

How do I do that?

Thanks, Boda Cydo

You can use the functions provided by itertools to take a generator and produce a new generator.

For example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.

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

You can just wrap the generator in your own generator.

from itertools import count

def odd_count():
    for i in count():
        if i % 2:
            yield i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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