pymongo 的生成器函数

发布于 2024-11-25 10:43:32 字数 436 浏览 3 评论 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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月光色 2024-12-02 10:43:32

首先,删除return,这是没有必要的。

您的问题不在于 test() ,而在于您如何调用它。不要只调用 test()

做这样的事情:

for item in test():
    print item

你一次会得到一件物品。这基本上是在做:

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

while True:
    try:
        item = it.next()
    except StopIteration:
        break
    print item

First of all, remove return, it's not necessary.

Your problem isn't with test() but how you're calling it. Don't just call test().

Do something like:

for item in test():
    print item

And you'll get one item at a time. What this is doing is basically:

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

while True:
    try:
        item = it.next()
    except StopIteration:
        break
    print item
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文