Python 嵌套迭代-for和while循环之间的差异
我需要在生成器(而不是列表)上进行嵌套迭代。 我需要的是执行如下操作:Python 嵌套迭代-for和while循环之间的差异,python,for-loop,while-loop,iterator,itertools,Python,For Loop,While Loop,Iterator,Itertools,我需要在生成器(而不是列表)上进行嵌套迭代。 我需要的是执行如下操作: 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 wit
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
from itertools import *
princ_iter= count(3)
while True:
x = next(princ_iter)
print("testing ", x, "...")
...
但它不起作用,因为主迭代器(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 ...
因此,我尝试在循环中使用相同的指令:
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
from itertools import *
princ_iter= count(3)
while True:
x = next(princ_iter)
print("testing ", x, "...")
...
这一次我得到了我想要的结果
为什么这两个说明之间存在这种差异?有没有(更好的)方法使用for循环来实现这一点?这是文档中提到的行为:
一旦tee()
进行拆分,就不应使用原始的iterable
其他任何地方;否则,iterable
在没有
正在通知的对象
使用for循环时,始终使用原始迭代器:
for循环将始终使用同一对象
事实上:
princ_iter, nested_iter = tee(princ_iter)
用新的迭代器重新分配prince\u iter
变量是不相关的
另一方面,在while循环中,这是相关的,因为您正在控制什么是迭代器:
x = next(princ_iter)
i、 例如,prince\u iter
当前引用的任何迭代器,因此变量重新赋值确实会影响事情。不要使用iter
或任何其他内置函数的名称作为变量的名称。谢谢,我想是这样的。所以没有办法在for循环上执行它?@Ohibò这是实际的用例吗?比如,您正在使用itertools.count
?@juanpa.arrivilaga不,这只是一个玩具示例来解释我的观点。在我的例子中,迭代器的类型是pdDataframe.iterrows()
。在任何情况下,我都希望看到一个有价值的解决方案iterators@Ohib是的,我想不出使用for循环的通用方法。另一方面,通常应避免使用pandas.DataFrame.iterrows
。@juanpa.arrivilaga我知道,但我在数据帧中记录了一个操作列表,对于每个操作,我需要检查随后执行的操作,并对其进行一些计算。因此,我不知道如何在没有循环的情况下实现它