Skipping yield in python

放肆的年华 提交于 2019-12-10 11:15:19

问题


I'm writing a generator that takes an iterable and an integer n. For example if I call my generator:

generator('abcdefg',2)

then it should yield a, d, g skipping 2 letters.

When I call iter(iterable) then use yield next the yield automatically skips 1 letter. How would I tell python to skip yielding so I can skip n letters?


回答1:


Your generator is effectively islice with a step parameter, so you could wrap the original iterable as such:

from itertools import islice

def generator(iterable, skip):
    return islice(iterable, None, None, skip+1)

for item in generator('abcdefg', 2):
    print(item)
# a
# d
# g

If you wanted to write it by hand, then perhaps a simple way to understand is first yield'ing from the iterable, then consuming from the iterable the gap size...

def generator(iterable, skip):
    it = iter(iterable)
    while True:
        yield next(it)
        for _ in range(skip):
            next(it)



回答2:


This might be what you want

def generator(string, skip):
    for i,c in enumerate(string):
        if i % (skip+1)==0:
            yield c

This doesn't actually "skip" yield statements, that is every yield is executed. However, yield is only called at fixed intervals of the iteration over string characters.




回答3:


The basic framework using a custom iterator:

class skipper():
    def __init__(self, iterable, skip_count):
        self.it = iter(iterable)
        self.skip = skip_count
    def __iter__(self):
        return self
    def __next__(self):
        value = next(self.it)
        for _ in range(self.skip):
            next(self.it, None)
        return value

You could easily add any other behaviour you needed to this class.




回答4:


You can do this by simply using next() function

def make_generator():
    for x in range(1, 10):
        yield x


my_generator = make_generator()


def generator(temp_generator, num):  # generator('abcdefg',2)
    for x in range(num):
        next(temp_generator)
    for y in temp_generator:
        print(y)  # Skipped Value of generator
generator(my_generator, 2)

Output: 3 4 5 6 7 8 9



来源:https://stackoverflow.com/questions/23381257/skipping-yield-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!