用python顺时针打印矩阵
时间: 2023-02-18 07:26:04 浏览: 72
以下是一个示例:
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(matrix[i][j], end=" ")
print()
输出结果:
1 2 3
4 5 6
7 8 9
相关问题
python顺时针打印
你可以使用以下代码来实现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`函数,它将返回按顺时针顺序打印的列表。
python矩阵顺时针旋转
在Python中,可以使用以下代码实现矩阵的顺时针旋转:
```python
def rotate_matrix(matrix):
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = matrix[i][j]
matrix[i][j] = matrix[n - j - 1][i]
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]
matrix[j][n - i - 1] = temp
return matrix
```
以上代码中,`rotate_matrix`函数接受一个二维矩阵作为输入,然后通过交换矩阵的元素实现顺时针旋转。具体实现是通过遍历矩阵的每个层级,然后在每个层级上进行元素交换。