python顺时针打印
时间: 2023-07-17 18:55:41 浏览: 43
你可以使用以下代码来实现Python中列表顺时针打印的功能:
```python
def print_clockwise(matrix):
if not matrix: # 空矩阵
return []
# 初始化边界
top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
direction = 0 # 方向控制,0表示向右,1表示向下,2表示向左,3表示向上
result = []
while top <= bottom and left <= right:
if direction == 0: # 向右
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
elif direction == 1: # 向下
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
elif direction == 2: # 向左
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
elif direction == 3: # 向上
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
direction = (direction + 1) % 4
return result
```
你可以将要打印的矩阵作为参数传递给`print_clockwise`函数,它将返回按顺时针顺序打印的列表。