search

Home  >  Q&A  >  body text

Iterating over data with generator running in file and IDLE results inconsistently,

Using the generator to iterate the data construction loss problem, the same code running results are inconsistent:

  1. The result of running in file mode is: 5 2 1 0

  2. 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)

过去多啦不再A梦过去多啦不再A梦2776 days ago621

reply all(1)I'll reply

  • 迷茫

    迷茫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)
            

    reply
    0
  • Cancelreply