簡體   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