我是靠谱客的博主 糊涂萝莉,最近开发中收集的这篇文章主要介绍pythonfor循环和程序,Python中的生成器和for循环,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

So I have a generator function, that looks like this.

def generator():

while True:

for x in range(3):

for j in range(5):

yield x

After I load up this function and call "next" a bunch of times, I'd expect it to yield values

0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...

But instead it just yields 0 all the time. Why is that?

>>> execfile("test.py")

>>> generator

>>> generator().next()

0

>>> generator().next()

0

>>> generator().next()

0

>>> generator().next()

0

>>> generator().next()

0

>>> generator().next()

0

>>> generator().next()

0

解决方案

generator() initializes new generator object:

In [4]: generator() is generator() # Creating 2 separate objects

Out[4]: False

Then generator().next() gets the first value from the newly created generator object (0 in your case).

You should call generator once:

In [5]: gen = generator() # Storing new generator object, will reuse it

In [6]: [gen.next() for _ in range(6)] # Get first 6 values for demonstration purposes

Out[6]: [0, 0, 0, 0, 0, 1]

Note: generator.next was removed from Python 3 (PEP 3114) - use the next function instead:

In [7]: next(gen)

Out[7]: 1

最后

以上就是糊涂萝莉为你收集整理的pythonfor循环和程序,Python中的生成器和for循环的全部内容,希望文章能够帮你解决pythonfor循环和程序,Python中的生成器和for循环所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部