python数组螺旋打印
时间: 2023-09-26 20:09:49 浏览: 52
要实现Python中二维数组的螺旋打印,可以使用循环和递归的方式进行处理。以下是一种实现方法:
```python
def spiral_print(matrix):
if not matrix:
return
rows = len(matrix)
cols = len(matrix[0])
# 定义螺旋打印的边界范围
top = 0
bottom = rows - 1
left = 0
right = cols - 1
while top <= bottom and left <= right:
# 从左到右打印上边界
for i in range(left, right+1):
print(matrix[top][i], end=" ")
top += 1
# 从上到下打印右边界
for i in range(top, bottom+1):
print(matrix[i][right], end=" ")
right -= 1
# 检查是否需要打印下边界
if top <= bottom:
# 从右到左打印下边界
for i in range(right, left-1, -1):
print(matrix[bottom][i], end=" ")
bottom -= 1
# 检查是否需要打印左边界
if left <= right:
# 从下到上打印左边界
for i in range(bottom, top-1, -1):
print(matrix[i][left], end=" ")
left += 1
# 测试代码
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
spiral_print(matrix)
```
上述代码中的`spiral_print`函数接受一个二维数组作为输入,并按照螺旋的顺序打印数组中的元素。你可以根据需要调整输入的二维数组。例如,使用上述给定的`matrix`输入,将会打印出:1 2 3 6 9 8 7 4 5。