【问题标题】:Nesting iteration - difference between for and while loops嵌套迭代 - for 和 while 循环之间的区别
【发布时间】:2021-08-16 11:44:09
【问题描述】:

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

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 循环的方法?

【问题讨论】:

  • 不要使用iter或任何其他内置函数的名称作为变量的名称。

标签: python for-loop while-loop iterator itertools


【解决方案1】:

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

一旦tee() 进行了拆分,就不应使用原来的iterable 其他任何地方;否则,iterable 可以在没有 tee 对象被通知。

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

for x in princ_iter:
    ...

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

事实是:

princ_iter, nested_iter = tee(princ_iter)

用新的迭代器重新分配prince_iter 变量是无关紧要的。

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

x = next(princ_iter)

即,prince_iter 当前引用的任何迭代器,因此变量重新分配确实会影响事物。

【讨论】:

  • 谢谢,我想是这样的。所以没有办法通过 for 循环来执行它?
  • @Ohibò 这是实际的用例吗?比如,你使用的是itertools.count?
  • @juanpa.arrivilaga 不,这只是解释我的观点的玩具示例。在我的例子中,迭代器的类型是pdDataframe.iterrows()。无论如何,我希望为所有迭代器找到一个可行的解决方案
  • @Ohibò 是的,我想不出使用 for 循环的通用方法。顺便说一句,通常应该避免使用pandas.DataFrame.iterrows。
  • @juanpa.arrivilaga 我知道,但我有一个记录在数据框中的操作列表,对于每个操作,我需要检查随后执行了哪些操作并对它们进行一些计算。所以我不知道如何在没有循环的情况下做到这一点
猜你喜欢
  • 2016-08-02
  • 2021-05-12
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2012-06-05
  • 1970-01-01
相关资源
最近更新 更多