pymongo 的生成器函数
我正在尝试创建一个生成器函数,在每次调用时生成一个项目,但是我不断获得相同的项目。这是我的代码:
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
I am trying to make a generator function that yields an item on each call, however I keep getting the same item. Here is my code:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,删除
return
,这是没有必要的。您的问题不在于
test()
,而在于您如何调用它。不要只调用test()
。做这样的事情:
你一次会得到一件物品。这基本上是在做:
First of all, remove
return
, it's not necessary.Your problem isn't with
test()
but how you're calling it. Don't just calltest()
.Do something like:
And you'll get one item at a time. What this is doing is basically: