python将二维数组围绕指定竖轴线旋
时间: 2023-12-29 21:05:15 浏览: 50
转90度的代码:
```python
def rotate(matrix, axis):
# 翻转数组
for i in range(len(matrix)):
j = 0
k = len(matrix[i])-1
while j < k:
matrix[i][j], matrix[i][k] = matrix[i][k], matrix[i][j]
j += 1
k -= 1
# 交换元素
for i in range(len(matrix)):
for j in range(i+1, len(matrix[i])):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 围绕指定竖轴线翻转
if axis == 'left':
for i in range(len(matrix)):
j = 0
k = len(matrix[i])-1
while j < k:
matrix[i][j], matrix[i][k] = matrix[i][k], matrix[i][j]
j += 1
k -= 1
elif axis == 'right':
for i in range(len(matrix)):
j = 0
k = len(matrix[i])-1
while j < k:
matrix[i][j], matrix[i][k] = matrix[i][k], matrix[i][j]
j += 1
k -= 1
for i in range(len(matrix)):
j = 0
k = len(matrix[i])-1
while j < k:
matrix[i][j], matrix[i][k] = matrix[i][k], matrix[i][j]
j += 1
k -= 1
return matrix
```
使用示例:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
axis = 'left'
result = rotate(matrix, axis)
print(result)
```
输出结果:
```
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
```
阅读全文