下面的代码应该打印多行
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
要在嵌套的for
和while
循环中断时打印。为什么不动呢?
发布于 2018-06-25 07:12:58
在尝试运行您的代码时,我遇到了一个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])
# [...]
我不确定这是否是不正确的中断/打印的原因,但它肯定会有所不同。
发布于 2018-06-25 06:36:41
代码可能打破了错误的循环,我可能是错的,,。对于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库。
发布于 2018-06-25 06:16:44
看起来代码块上的缩进是不正确的。有与for
语句对齐的else
语句,等等。Python使用缩进来分隔代码块,如下所示。仔细检查是否正确对齐,无论是在代码中,还是在这里复制的内容中。如果这里的问题中缩进不正确,请随意编辑它。
https://stackoverflow.com/questions/51014374
复制相似问题