【问题标题】:How can i return all values from for loop in python3 mongodb query如何在 python3 mongodb 查询中从 for 循环返回所有值
【发布时间】:2019-10-19 12:33:51
【问题描述】:

我有一个查询 mongodb 集合的函数

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        return x

我想返回集合中的所有内容而不将其打印到控制台。当我运行上面的代码时,我得到一个结果:

{'Date': testvalue, 'Open': testvalue, 'High': testvalue, 'Low': testvalue, 'Close': testvalue, 'Volume':testvalue}

当我跑步时

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        print(x)

我从我的收藏中获取每一个文档,这就是我想要的。 如何让代码返回每个文档而不是使用print

【问题讨论】:

  • 怎么样,省略循环,return list(findInMongo)?

标签: python jquery mongodb find return


【解决方案1】:

问题是您使用的是return,而您可能需要yield

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        return x # This will exit after the first result

return 退出函数,它从函数中返回一个值,退出作用域。另一方面,yield 将继续生成值,直到迭代器耗尽(或findInMongofor 循环中没有更多元素)。

相反,做

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    for x in findInMongo:
        yield x

# which allows you to do
vals = list(checkDb())

因为checkDb() 现在是一个迭代器(或者更具体地说,是一个生成器)。之后的python3版本也引入了好看的yield from语法

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    yield from findInMongo # yield from a collection directly

或者,如果这是一个迭代器,你可以只返回 findInMongo

def checkDb():
    signals =  mydb['collection']
    findInMongo =  signals.find({}, {'_id': False})
    return findInMongo # return the iterator directly

所有这些都将支持list(checkDb())[x for x in checkDb()] 语法

【讨论】:

  • 谢谢你是有道理的,两个代码示例对我来说都很完美:)
  • 很高兴听到,如果答案对您有用,请随时接受。如果您需要任何额外的说明,或者这不能回答您的问题,您可以提出修改建议。编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 2013-05-15
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 2012-03-01
相关资源
最近更新 更多