Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
これは、yield の使用をテストするためのサンプル スクリプトです...間違っていますか? 常に「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
毎回新しいジェネレーターを作成しています。一度だけ呼び出しtestGen()て、返されたオブジェクトを使用する必要があります。試す:
testGen()
w = 0 g = testGen() while w < 10: print g.next() w += 1
そしてもちろん、通常の慣用的なジェネレーターの使用法があります。
for n in testGen(): print n
testGen()これは、反復ごとに 1 回ではなく、ループの開始時に 1 回だけ呼び出されることに注意してください。