奇数嵌套循环不能正确中断(Python3.x)

2024-06-16 09:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码应该打印多行

1
2
3

夹杂着一排排

0

但是,它实际打印的是多行

1
1
1
1
3

夹杂着一排排

0

代码:

boxes = []
for y in range(len(hmap)):
    for x in range(len(hmap[y])):
        w = 4
        h = 4

        minh = hmap[y][x]
        maxh = hmap[y][x]

        htemp = h
        while True:
            if y + htemp > len(hmap): break

            passes = False
            wtemp = w
            while True:
                if x + wtemp > len(hmap[y]): break

                for c in range(x, x+wtemp):
                    for r in range(y, y+htemp):
                        minh = min(minh,hmap[c][r])
                        maxh = max(maxh,hmap[c][r])

                        if maxh - minh > v:
                            print('1')
                            break
                    else:
                        print('2')
                        break
                else:
                    print('3')
                    break

                print('0')
                passes = True
                wtemp += 1

            if passes:
                boxes.append([x,y,wtemp-1,htemp])

            htemp += 1

            if not passes: break
  • hmap是一个由浮点值组成的二维数组,传递给该代码所在的函数。你知道吗

这段代码应该生成一系列矩形,供其他(不相关的)代码部分稍后使用。“通过”(最小值/最大值的差值不大于v)的矩形会导致

0

待打印。不“通过”的矩形应该引起

1
2
3

当嵌套的forwhile循环中断时打印。为什么不起作用?你知道吗


Tags: 代码inforlenifrangeprintbreak
3条回答

代码可能会破坏错误的循环,我可能会出错。 对于while循环,生成一个布尔变量并将其设置为true。然后在while循环中,在需要时使用if语句使其为false。你知道吗

top_loop, bottom_loop = True, True
while top_loop:
    # do something
    while bottom_loop:
        # do something
        if condition:
            top_loop = False

我还没想过for循环。 在这个链接上有一个答案,为循环命名并打破for循环。它使用contextlib库。你知道吗

Link

看起来代码块上的缩进不正确。有else语句与for语句对齐,等等。仔细检查代码或复制的内容是否正确对齐。如果缩进在这里的问题是不正确的,请随意编辑它。你知道吗

在尝试运行代码时,我遇到了IndexError: list index out of range错误。看起来您可能已经转置了列和行索引。尝试将[c][r]下标更改为[r][c]

# [...]
            for c in range(x, x+wtemp):
                for r in range(y, y+htemp):
                    minh = min(minh,hmap[r][c])
                    maxh = max(maxh,hmap[r][c])
# [...]

我不确定这是否是不正确的中断/打印的原因,但它肯定会造成不同。你知道吗

相关问题 更多 >