n = int(input("请输入一个大于1的整数n: ")) matrix = [[0] * n for _ in range(n)] num = 1 left, right, top, bottom = 0, n-1, 0, n-1 while num <= n*n: for i in range(left, right+1): matrix[top][i] = num num += 1 for i in range(top+1, bottom+1): matrix[i][right] = num num += 1 for i in range(right-1, left-1, -1): matrix[bottom][i] = num num += 1 for i in range(bottom-1, top, -1): matrix[i][left] = num num += 1 left, right, top, bottom = left+1, right-1, top+1, bottom-1给我加个输出函数
时间: 2024-03-14 15:46:52 浏览: 61
好的,这里是加上输出函数的完整代码:
```python
def print_matrix(matrix):
for row in matrix:
print(row)
n = int(input("请输入一个大于1的整数n: "))
matrix = [[0] * n for _ in range(n)]
num = 1
left, right, top, bottom = 0, n-1, 0, n-1
while num <= n*n:
for i in range(left, right+1):
matrix[top][i] = num
num += 1
for i in range(top+1, bottom+1):
matrix[i][right] = num
num += 1
for i in range(right-1, left-1, -1):
matrix[bottom][i] = num
num += 1
for i in range(bottom-1, top, -1):
matrix[i][left] = num
num += 1
left, right, top, bottom = left+1, right-1, top+1, bottom-1
print_matrix(matrix)
```
在主程序中增加了一个名为 `print_matrix` 的函数,用于输出二维列表。在主程序中调用该函数即可输出二维列表。
例如,当输入 n=3 时,输出的二维列表为:
```
1 2 3
8 9 4
7 6 5
```
阅读全文