首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套迭代- for和while循环之间的差异

嵌套迭代- for和while循环之间的差异
EN

Stack Overflow用户
提问于 2021-05-28 08:15:52
回答 1查看 43关注 0票数 0

我需要在生成器(而不是列表)上执行嵌套迭代。我需要的是这样的表演:

代码语言:javascript
复制
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循环尝试了以下代码:

代码语言:javascript
复制
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)一起迭代,我得到这个输出:

代码语言:javascript
复制
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循环中使用相同的指令:

代码语言:javascript
复制
from itertools import *
princ_iter= count(3)
while True:
    x = next(princ_iter)
    print("testing ", x, "...")
...

而这一次,我得到了我正在寻找的确切输出!

为什么这两种指令有这样的区别呢?有(更好的)方法来使用for循环吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-28 08:35:30

这是tee文档中提到的行为

一旦tee()进行了拆分,就不应该在其他任何地方使用原始iterable;否则,在不通知tee对象的情况下,iterable可能会得到高级处理。

当您使用for-循环时,原始迭代器将一直被使用。

代码语言:javascript
复制
for x in princ_iter:
    ...

for-循环将始终与同一个对象一起工作。

事实是:

代码语言:javascript
复制
princ_iter, nested_iter = tee(princ_iter)

用新的迭代器重新分配prince_iter变量是不相关的。

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

代码语言:javascript
复制
x = next(princ_iter)

也就是说,不管prince_iter当前所引用的迭代器是什么,所以变量重分配确实会对事情产生影响。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67735263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档