嵌套迭代 - for 和 while 循环的区别

Nesting iteration - difference between for and while loops

我需要对生成器(不是列表)进行嵌套迭代。 我需要的是执行这样的操作:

testing  3 ...
Testing passed!
     Starting subtest:
     Sub-testing 4  with  3
     Sub-testing passed!
testing  4 ...
testing  5 ...
testing  6 ...
Testing passed!
     Starting subtest:
     Sub-testing 7  with  6
     Sub-testing 8  with  6
     Sub-testing 9  with  6
     Sub-testing passed!
testing  7 ...
testing  8 ...
testing  9 ...
Testing passed!
     Starting subtest:
     Sub-testing 10  with  9
     Sub-testing 11  with  9
     Sub-testing 12  with  9
     Sub-testing passed!
testing  10 ...

所以我尝试了以下代码,使用 for 循环:

from itertools import *
princ_iter = count(3)
for x in princ_iter:
    print("testing ", x, "...")
    if x % 3 == 0:
        print("Testing passed!")
        print("     Starting subtest:")
        princ_iter, nested_iter = tee(princ_iter)
        for y in nested_iter:
            print("     Sub-testing", y, " with ", x)
            if y % (x//2) == 0:
                print("     Sub-testing passed!")
                break

但它不起作用,因为主迭代器 (princ_iter) 与嵌套迭代器 (nested_iter) 一起迭代,我得到了这个输出:

testing  3 ...
Testing passed!
     Starting subtest:
     Sub-testing 4  with  3
     Sub-testing passed!
testing  5 ...
testing  6 ...
Testing passed!
     Starting subtest:
     Sub-testing 4  with  6
     Sub-testing 7  with  6
     Sub-testing 8  with  6
     Sub-testing 9  with  6
     Sub-testing passed!
testing  10 ...
testing  11 ...

所以我尝试在 while 循环中使用相同的指令:

from itertools import *
princ_iter= count(3)
while True:
    x = next(princ_iter)
    print("testing ", x, "...")
...

这次我得到了我想要的输出!

为什么这两个指令之间存在这种差异?是否有使用 for 循环的(更好的)方法?

tee 的文档中提到了这种行为:

Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

当您使用 for 循环时,原始迭代器一直在使用:

for x in princ_iter:
    ...

for 循环将始终处理同一个对象

事实是:

princ_iter, nested_iter = tee(princ_iter)

重新分配 prince_iter 变量 与新迭代器无关。

另一方面,在您的 while 循环中,此 相关的,因为您正在控制高级迭代器:

x = next(princ_iter)

即,prince_iter 当前引用的任何迭代器 ,因此变量重新赋值 影响事物.