Using the generator to iterate the data construction loss problem, the same code running results are inconsistent:
The result of running in file mode is: 5 2 1 0
Python comes with IDLE and the result is: 5 3 2 1 0
def countdown(n):
while n >= 0:
newvalue = (yield n)
if newvalue is not None:
n = newvalue
else:
n -= 1
c = countdown(5)
for n in c:
print(n)
if n == 5:
c.send(3)
迷茫2017-05-18 11:03:04
Do not modify the object being traversed, as this will cause index confusion and fail to achieve the results we want. You can use enumerate to view the changes in the index during the traversal process
for index, n in enumerate(c):
# index 为取到的索引值
print(index, n)
if n == 5:
c.send(3)