0

呼び出しごとにアイテムを生成するジェネレーター関数を作成しようとしていますが、同じアイテムを取得し続けます。これが私のコードです:

  1 from pymongo import Connection
  2 
  3 connection = Connection()
  4 db = connection.store
  5 collection = db.products
  6 
  7 def test():
  8         global collection #using a global variable just for the test.
  9         items = collection.find()
  10        for item in items:
  11                 yield item['description']
  12        return
4

1 に答える 1

1

まず、削除returnします。必要ありません。

あなたの問題は問題ではありませんtest()が、あなたがそれをどのように呼んでいるのかです。ただ電話しないでくださいtest()

次のようなことをします:

for item in test():
    print item

そして、一度に1つのアイテムを取得します。これが行っていることは基本的に:

from exceptions import StopIteration
it = iter(test())

while True:
    try:
        item = it.next()
    except StopIteration:
        break
    print item
于 2011-07-20T06:43:00.130 に答える