【发布时间】:2022-12-12 14:29:37
【问题描述】:
考虑以下代码:
from itertools import chain
lst = ['a', 1, 2, 3, 'b', 4, 5, 'c', 6]
def nestedForLoops():
it = iter(lst)
for item0 in it:
if isinstance(item0, str):
print(item0)
else:
# this shouldn't happen because of
# 1. lst[0] is a str, and
# 2. line A
print(f"this shouldn't happen: {item0=}")
pass
for item1 in it:
if not isinstance(item1, int):
break
print(f'\t{item1}')
else: # no-break
# reached end of iterator
return
# reached a str
assert isinstance(item1, str)
it = chain(item1, it) # line A
nestedForLoops()
我期待它打印
a
1
2
3
b
4
5
c
6
但它打印了
a
1
2
3
this shouldn't happen: item0=4
this shouldn't happen: item0=5
c
this shouldn't happen: item0=6
我使用 while 循环而不是 for 循环编写了我认为等效的代码:
from itertools import chain
lst = ['a', 1, 2, 3, 'b', 4, 5, 'c', 6]
def nestedWhileLoops():
it = iter(lst)
while True:
try:
item0 = next(it)
except StopIteration:
break
if isinstance(item0, str):
print(item0)
else:
# this shouldn't happen because of
# 1. lst[0] is a str, and
# 2. line B
print(f"this shouldn't happen: {item0=}")
pass
while True:
try:
item1 = next(it)
except StopIteration:
# reached end of iterator
return
if not isinstance(item1, int):
break
print(f'\t{item1}')
# reached a str
assert isinstance(item1, str)
it = chain(item1, it) # line B
nestedWhileLoops()
它确实打印出我所期望的,即
a
1
2
3
b
4
5
c
6
那么为什么nestedForLoops 的行为与nestedWhileLoops 不同?
【问题讨论】:
-
当您使用调试器逐步执行
nestedForLoops时,每一行的行为是否都符合您的预期? How to step through Python code to help debug issues? 如果您正在使用 IDE,现在是学习其调试功能的好时机。在战略点打印内容可以帮助您追踪正在发生或未发生的事情。 What is a debugger and how can it help me diagnose problems?
标签: python nested iterator generator nested-loops