gpt4 book ai didi

Python 的每个循环不起作用

转载 作者:行者123 更新时间:2023-12-01 03:19:09 24 4
gpt4 key购买 nike

我正在循环一个列表,在该循环内我正在循环一些从 mongodb 获取的文档。但在输出控制台中我只能看到一次迭代。但外层循环工作正常。当我调试时,它进入外循环,但不进入内循环。请帮帮我。

client = MongoClient('mongodb://localhost:27017/')
db = client['mydb']
documents = icps_db.user.find({})
name_set = ['john', 'marshal', 'ann' ...]

for name in name_set:
print(name)
for idx, document in enumerate(documents):
print (documents)
if name in document["filtered_words"]:
print ("Found " + name)
else:
print (name + " not found in document ")

输出在第二次迭代中,它没有到达行: print (str(idx))。

    john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
john
marshal
marshal

最佳答案

问题出在这里:

documents = icps_db.user.find({}) 

在对文档进行第一组迭代后,光标将被用完。它是一个只读容器。您要么需要缓存结果,要么在内部循环之前执行 documents.rewind()

要缓存结果,请执行以下操作:

documents = list(icps_db.user.find({})) 

我不太了解 MongoDB,因此每个文档可能都有某种使用游标的实时回调(我对此表示怀疑)。如果是这样,简单的缓存将不起作用。

另一个解决方案是使用 rewind() :

Rewind this cursor to its unevaluated state.

Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor.

像这样使用它:

for name in name_set:
documents.rewind()
for idx, document in enumerate(documents):
...

关于Python 的每个循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com