为什么运行结果会多一个数字6?
我想按顺时针顺序依次输出矩阵中的元素:,
, →
代码:
matrix = [,,]
right = len(matrix)
left = 0
bottom = len(matrix)
top = 0
result = []
while left < right and top < bottom:
#从左到右遍历元素
for i in range(left,right):
result.append(matrix)
#从上到下遍历元素
for j in range(top+1,bottom):
result.append(matrix)
#从右到左遍历元素
for x in range(right-2,left-1,-1):
result.append(matrix)
#从下到上
for y in range(bottom-2,top,-1):
result.append(matrix)
#外层遍历结束后继续遍历内层
left = left + 1
right = right - 1
bottom = bottom - 1
top = top + 1
print(result)
输出结果
问题出在代码的最后一行,即print(result)。在最后一次循环结束后,left、right、bottom和top的值都会发生变化,所以会多输出一个数字6。
在最后一次循环结束后,left = 1,right = 2,bottom = 2,top = 1。此时,由于left < right和top < bottom条件不满足,循环结束。但是在循环结束后,left = 2,right = 1,bottom = 1,top = 2。所以在最后一次循环中,result.append(matrix)这一行代码会被执行,将数字6添加到result列表中。
要解决这个问题,可以在print(result)之前添加一行代码来移除最后一个数字6,例如result.pop()。这样就可以得到正确的输出结果。
修改后的代码如下:
matrix = [,,]
right = len(matrix)
left = 0
bottom = len(matrix)
top = 0
result = []
while left < right and top < bottom:
#从左到右遍历元素
for i in range(left,right):
result.append(matrix[ i])
#从上到下遍历元素
for j in range(top+1,bottom):
result.append(matrix)
#从右到左遍历元素
for x in range(right-2,left-1,-1):
result.append(matrix)
#从下到上
for y in range(bottom-2,top,-1):
result.append(matrix)
#外层遍历结束后继续遍历内层
left = left + 1
right = right - 1
bottom = bottom - 1
top = top + 1
result.pop()
print(result)
页:
[1]