为什么我的while循环条件变量没有分配就突变了?

时间:2019-05-07 16:21:12

标签: python while-loop variable-assignment

我有以下永无休止的while循环:

i = len(taglist) - 1
while(i >= 0):
    print("i, at the beginning: " + str(i))
    tag = taglist[i]
    label = tag["tagname"]
    merged_polygon = tag["polygon"]
    merged_indices = [i]
    print("i, a little further: " + str(i))
    for j in range(i * num_passes):
        print("i, in the for-loop: " + str(i))
        if taglist[j % i]["tagname"] == label and len(intersect(taglist[j % i]["polygon"], merged_polygon)) > 0:
            merged_polygon = unite(taglist[j % i]["polygon"], merged_polygon)
            merged_indices.append(j)
            print("i, at the end of the for-loop: " + str(i))
    taglist = [t for i, t in enumerate(taglist) if i not in merged_indices]
    print("i, after the for-loop: " + str(i))
    tag["polygon"] = merged_polygon
    tag["bbox"] = bound_box(merged_polygon)
    taglist.append(tag)
    print("i, before update: " + str(i))
    i = min([i - 1, len(taglist) - 2])
    print("i, after update: " + str(i))

这将导致反复打印以下结果:

...
i, at the beginning: 1
i, a little further: 1
i, in the for-loop: 1
i, in the for-loop: 1
i, in the for-loop: 1
i, in the for-loop: 1
i, in the for-loop: 1
i, after the for-loop: 2
i, before update: 2
i, after update: 1
...

在嵌套的for循环之后,我的while循环条件变量(i)正在递增,而我没有这样做。为什么是这样?我只想在while循环结束时更改ì

1 个答案:

答案 0 :(得分:1)

您在i之前更改print

taglist = [t for i, t in enumerate(taglist) if i not in merged_indices]