我有一个类似
的矩阵matrix1 = [1,2
3,4]
matrix2 =[1,2,3
4,5,6
7,8,9]
我希望通过某个步骤旋转此矩阵,如r = 1,然后输出就像
output_matrix = [3,1
4,2]
output_matrix = [4,1,2
7,5,3
8,9,6]
如何实现这一点,步骤的旋转将是动态的。
我找到了这个解决方案,但这是针对固定旋转的,即。步骤= 1
def rotateMatrix(mat):
if not len(mat):
return
top = 0
bottom = len(mat)-1
left = 0
right = len(mat[0])-1
while left < right and top < bottom:
# Store the first element of next row,
# this element will replace first element of
# current row
prev = mat[top+1][left]
# Move elements of top row one step right
for i in range(left, right+1):
curr = mat[top][i]
mat[top][i] = prev
prev = curr
top += 1
# Move elements of rightmost column one step downwards
for i in range(top, bottom+1):
curr = mat[i][right]
mat[i][right] = prev
prev = curr
right -= 1
# Move elements of bottom row one step left
for i in range(right, left-1, -1):
curr = mat[bottom][i]
mat[bottom][i] = prev
prev = curr
bottom -= 1
# Move elements of leftmost column one step upwards
for i in range(bottom, top-1, -1):
curr = mat[i][left]
mat[i][left] = prev
prev = curr
left += 1
return mat
matrix =[[1,2,3],[4,5,6], [7,8,9]]
matrix = rotateMatrix(matrix)
# # Print modified matrix
print(matrix)
答案 0 :(得分:0)
def rotate(r,matrix):
'''for rotating the values on the outer ring of a matrix of size HxW'''
height = len(matrix)
width = len(matrix[0])
matrixMap = mapMatrix(height,width)
r %= len(matrixMap)
rotatedMap = matrixMap[-r:]+matrixMap[:-r]
newMatrix = {el:matrix[el[0]][el[1]] for el in matrixMap}
for i,el in enumerate(rotatedMap):
matrix[matrixMap[i][0]][matrixMap[i][1]] = newMatrix[el]
return matrix
def mapMatrix(h,w):
matrix = []
for i in range(w):
matrix.append((0,i))
for i in range(1,h):
matrix.append((i,w-1))
for i in range(w-2,-1,-1):
matrix.append((h-1,i))
for i in range(h-2,0,-1):
matrix.append((i,0))
return matrix
这是我实施它的方式,但我认为仍有一些改进空间。支持负r。希望这会有所帮助。
答案 1 :(得分:-1)
你可以结合旋转和移调来获得你想要的东西
import numpy as np
m = np.array([[1,2],[3,4]], int)
m1 = np.rot90(m)
m2 = m1.transpose()
print (m2)
这会给你
[[2 1]
[4 3]]
根据您的意愿改变。
实际上你可以选择这样的元素
import numpy as np
m = np.array([[1,2],[3,4]], int)
# create tuple
new = (m[0][1],m[1][0])
# print list
print (list(new))
[2, 3]