简体   繁体   中英

Why my Python test generator simply doesn't work?

This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'...

#!/usr/bin/python

def testGen():
    for a in [1,2,3,4,5,6,7,8,9,10]:
         yield a

w = 0
while w < 10:
    print testGen().next()
        w += 1

You're creating a new generator each time. You should only call testGen() once and then use the object returned. Try:

w = 0
g = testGen()
while w < 10:
    print g.next()
    w += 1

Then of course there's the normal, idiomatic generator usage:

for n in testGen():
    print n

Note that this will only call testGen() once at the start of the loop, not once per iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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