Skipping yield in python

一个人想着一个人 提交于 2019-12-06 08:35:58

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)

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.

Ethan Furman

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.

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

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