以下代码输出大小为(n * n)
的螺旋矩阵
def generateMatrix(self, a):
#generates a list with specified elemnts from 1 to n^2
x = [list(range(i, i+a)) for i in range(1, a**2, a)]
numrows = len(x)
numcols = len(x[0])
top = 0
bottom = numrows-1
left = 0
right = numcols-1
direction = 0
b = []
while (top <= bottom and left <= right):
if direction is 0:
for i in range(left, right+1):
b.append(x[top][i])
top += 1
elif direction is 1:
for i in range(top, bottom+1):
b.append(x[i][right])
right -= 1
elif direction is 2:
for i in range(right, left-1, -1):
b.append(x[bottom][i])
bottom -= 1
elif direction is 3:
for i in range(bottom, top-1, -1):
b.append(x[i][left])
left += 1
direction = (direction+1) % 4
return b
在线IDE中运行此代码时我得到了 TypeError:&#39; int&#39;对象不可迭代。 我已经检查过我是否在代码中进行了错误的迭代。但是找不到任何问题。我知道之前已经问过这个问题,我已经检查了解决方案。但没有任何工作。任何人都可以检查我的代码有什么问题吗?