Iterating over data with generator running in file and IDLE results inconsistently,
过去多啦不再A梦
过去多啦不再A梦 2017-05-18 11:01:04
0
1
549

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梦

reply all(1)
迷茫

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)
        
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!