简体   繁体   English

无限python发生器

[英]Infinite python generator

I have been leaning python and programming for not so long.我学习 python 和编程的时间不长。 So you may find my question silly.所以你可能会觉得我的问题很傻。 I am reviewing generator and try to generate 'yes', 'no' infinitely just to understand the concept.我正在审查生成器并尝试无限地生成“是”、“否”以理解这个概念。

I have tried this code but having "yes" each time我已经尝试过这段代码,但每次都“是”

def yes_or_no():
    answer = ["yes","no"]
    i=0
    while True:
        if i >=2:
            i=0
        yield answer[i]
        i+=1

c=next(yes_or_no())

print(c)
print(c)
print(c)
print(c)

yes_no() produces the generator; yes_no()产生生成器; you want to call next on the same generator each time, rather than printing the same first element over and over.您希望每次都在同一个生成器上调用next ,而不是一遍又一遍地打印相同的第一个元素。

c = yes_no()

print(next(c))
print(next(c))
# etc.

That said, there's no need for a separate counter;也就是说,不需要单独的计数器; just yield yes , then yield no , then repeat.只是 yield yes ,然后 yield no ,然后重复。

def yes_or_no():
    while True:
        yield "yes"
        yield "no"

You need to initialize the generator and then call next on the initialized generator object:您需要初始化生成器,然后在初始化的生成器 object 上调用next

c = yes_or_no()

Now you need to call next on c :现在您需要在c上调用next

print(next(c))
print(next(c))

In your current code c=next(yes_or_no()) :在您当前的代码c=next(yes_or_no())

  • yes_or_no() will initialize the generator and calling next on it will get the first yes and you're saving that yes as name c yes_or_no()将初始化生成器并调用next将得到第一个yes并且您将yes保存为名称c

  • In the next lines, you're just printing same yes referred by c while doing print(c)在接下来的几行中,您只是在执行print(c)时打印c引用的相同yes

While your function does return a generator and it has been stated by others that all you need to do is iterate over it using a loop or calling next in succession.虽然您的 function 确实返回了一个生成器,并且其他人已经说过,您需要做的就是使用循环对其进行迭代或连续调用 next 。 Python provides you a great library called itertools to do exactly this thing; Python 为您提供了一个名为itertools的出色库来执行此操作; it's called itertools.cycle .它被称为itertools.cycle This is all the code you need to replicate your functions ability:这是复制功能所需的所有代码:

def yes_no():
    return itertools.cycle(['yes', 'no'])

And just like others have said, a generator can be iterated over using next or a loop.就像其他人所说的那样,可以使用next或循环来迭代生成器。

>>> c = yes_no()
>>> next(c) 
'yes'
>>> next(c) 
'no'
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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