使用其他功能更改生成器-Python 3.x [英] Changing a generator with another function - Python 3.x

查看:84
本文介绍了使用其他功能更改生成器-Python 3.x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面更改生成器的行为,以使其仅产生偶数.我怎样才能做到这一点?

I want to change the behavior of the generator below so that it only yields even numbers. How can I do this?

我知道有更简单,聪明的方法可以做到这一点.这是人为的人力资源挑战,其中

I'm aware that there simpler, clever ways to do this. This is a contrived HR challenge, where the

我编写的change_generator函数无法产生所需的输出. 我只能更改change_generator .

The change_generator function that I wrote does not yield the desired output. I can only change change_generator.

我无法更改positive_integers_generator()或下面的for循环.

I cannot change positive_integers_generator() nor the for loop below.

我可以用装饰器解决这个问题吗?

Can I solve this with a decorator?

#can't change the body of this function
def positive_integers_generator():
    n = 1
    while True:
        x = yield n
        if x is not None:
            n = x
        else:
            n += 1

# can only change this function            
def change_generator(generator, n):
  for i in generator:
    if i%2 == 0:
      yield(i)



# can't change this code either
# should print 1, 2, 4, 6, 8
g = positive_integers_generator() 
for _ in range(5):
    n = next(g)
    print(n)
    change_generator(g, n)

推荐答案

您可以使用内置函数filter

even_numbers_generator = filter(lambda n: n % 2 == 0, positive_integers_generator())

或生成器表达式.

even_numbers_generator = (n for n in positive_integers_generator() if n % 2 == 0)

或者从标准库中 itertools.count :

Or itertools.count from the standard library:

even_numbers_generator = itertools.count(start=2, step=2)

但是,如果您只能更改change_generator函数,则对挑战的正确答案"可能涉及使用

But if you only can change the change_generator function, the "correct answer" to the challenge probably involves using generator.send()

# can only change this function            
def change_generator(generator, n):
    if n % 2 == 0:
        generator.send(n + 1)

这篇关于使用其他功能更改生成器-Python 3.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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