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

问题描述

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

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 ","...")
...

这一次我得到了我正在寻找的输出

为什么这两条指令之间存在这种差异?有没有(更好的)方法可以使用 for 循环来做到这一点?

解决方法

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

一旦 const PostItemBlock = styled.div` display: flex; width: 352px; flex-direction: column; padding-top: 0; padding-bottom: 3rem; p { margin-top: 2rem; } h3 { width: 352px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .subdesc { align-self: flex-end; } `; const Item = ({ item }) => { return ( <ItemBlock> <h3> title. </h3> <p1 className="subdesc">subdesc.</p1> </ItemBlock> ); }; 进行了拆分,不应使用原来的 tee() 其他任何地方;否则,iterable 可以在没有 通知对象。

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

iterable

for 循环将始终使用同一个对象

事实:

for x in princ_iter:
    ...

使用新迭代器重新分配 princ_iter,nested_iter = tee(princ_iter) 变量 无关紧要。

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

prince_iter

x = next(princ_iter) 当前引用的任何迭代器,因此变量重新分配确实会影响事情。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...