繁体   English   中英

奇怪的嵌套循环无法正确中断(Python 3.x)

[英]Odd Nested Loop Doesn't Break Properly (Python 3.x)

以下代码应打印多行

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是2D浮点值数组,该数组传递给此代码所在的函数。

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

0

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

1
2
3

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

尝试运行您的代码时,我遇到了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])
# [...]

我不确定这是否是错误的中断/打印的原因,但是肯定可以有所作为。

代码可能会打错循环, 我可能是错的 对于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循环和打破for循环。 它使用contextlib库。

链接

您的代码块上的缩进似乎不正确。 还有elsefor语句对齐for语句,等等。Python使用缩进来分隔这样的代码块。 仔细检查代码中或此处复制的内容是否正确对齐。 如果缩进在此问题中只是不正确,请随时对其进行编辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM