超级简单的嵌套 Pythonic for-in 循环无法正常运行......与输入有关

Super simple nested Pythonic for-in loops not functioning correctly... something to do with inputs

我有一段不工作的简单代码,我无法开始弄清楚原因。

代码如下:

def myFunction(otherDictionary, mongoDbCollection):

    for p in otherDictionary:

        print('hi')

        for d in mongoDbCollection:

            print('hello')

显然,最终目标不是打印一堆 hi's 和 hello's,而是在循环机制似乎无法正常运行时纯粹出于调试目的而这样做。

当我沮丧地调用此函数时,打印了一个 hi,然后是所有 hello,然后是其余的 hi。或者像这样:

hi
hello
hello
hello
hello
hi
hi
hi
hi

而不是:

hi
hello
hello
hello
hello
hi
hello
hello
hello
hello

等等……

它肯定与函数的输入有关,因为当我将 otherDictionary 和 mongoDbCollection 分别更改为 [1,2,3,4,5] 以调试此问题时,它打印了 hi's 和 hello's不出所料。

输入中有什么可能会导致此类问题?

mongoDbCollection = 来自我的 mongo 数据库的集合

otherDictionary 只是一个简单的字典,其中包含关键字和每个关键字的相应计数,如下所示:

{ 'randomKey': 10, 'otherRandomKey': 3, 'evenMoreRandomKey': 14 }

密钥中的奇怪 characters/symbols 会导致这样的错误吗?

我完全被难住了!代码太简单了,不能用...

我不使用 mongoDB,所以我在这里可能完全偏离了基础但是:

有没有可能mongoDbCollection是一个发电机?生成器只能迭代一次。第二次尝试迭代它时,它无法迭代,它基本上是一个空的可迭代对象。

这会导致类似于您在问题中显示的行为:初始 "hi" 将打印一次,mongoDbCollection 将通过打印迭代 "hello" x 次,然后 "hi" 将在第一个 for 循环的剩余部分打印。

看起来像这样:

hi
hello
hello
hello
# "hello" however many times are in mongoDbCollection ...
hi
hi
hi
# "hi" however many times are in otherDictionary ...

要修复它,您必须创建一个可以无限次迭代的对象(例如,列表或字典,任何与 mongoDbCollection 最匹配的对象)。

def myFunction(otherDictionary, mongoDbCollection):
    collection = list(mongoDbCollection) # or use dict or some other iterable object
    for p in otherDictionary:
        print('hi')
        for d in collection:
            print('hello')