我需要在生成器(而不是列表)上执行嵌套迭代。我需要的是这样的表演:
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循环吗?
发布于 2021-05-28 08:35:30
这是tee文档中提到的行为
一旦
tee()进行了拆分,就不应该在其他任何地方使用原始iterable;否则,在不通知tee对象的情况下,iterable可能会得到高级处理。
当您使用for-循环时,原始迭代器将一直被使用。
for x in princ_iter:
...for-循环将始终与同一个对象一起工作。
事实是:
princ_iter, nested_iter = tee(princ_iter)用新的迭代器重新分配prince_iter变量是不相关的。
另一方面,在while-循环中,这是相关的,因为您控制的迭代器是高级的:
x = next(princ_iter)也就是说,不管prince_iter当前所引用的迭代器是什么,所以变量重分配确实会对事情产生影响。
https://stackoverflow.com/questions/67735263
复制相似问题