简体   繁体   English

Python中,如何将矩阵逆时针旋转90度?

[英]In Python, how do I rotate a matrix 90 degrees counterclockwise?

>>> def rotate_matrix( k: List[List[int]]):
    """
    For example, if I have:
    m = [[1,2,3],
         [2,3,3],
         [5,4,3]]
    rotate_matrix(m) should give me [[3,3,3],[2,3,4],[1,2,5]]. 
    """

Edit: Preferably without numpy.编辑:最好没有 numpy。

Here is the counter clockwise matrix rotation as one line in pure python (ie, without numpy):这是逆时针矩阵旋转作为纯python中的一行(即,没有numpy):

new_matrix = [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

If you want to do this in a function, then如果您想在函数中执行此操作,那么

def rotate_matrix( m ):
    return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

and either way, the result for无论哪种方式,结果

m = [ [1,2,3], [2,3,3], [5,4,3]]

is

[[3, 3, 3], [2, 3, 4], [1, 2, 5]]

Aside, if you want the usual transpose, then the simple one line pure python version is另外,如果你想要通常的转置,那么简单的一行纯python版本是

[[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

You could use the numpy function rot90你可以使用 numpy 函数 rot90

import numpy as np
m = np.array([[1,2,3],
         [2,3,3],
         [5,4,3]])

def rotate_matrix(mat):
    return np.rot90(mat)
def rotate_90_degree_anticlckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0]), 0, -1):
        new_matrix.append(list(map(lambda x: x[i-1], matrix)))

    return new_matrix


def rotate_90_degree_clckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0])):
        li = list(map(lambda x: x[i], matrix))
        li.reverse()
        new_matrix.append(li)

    return new_matrix

def rotate_90_degree_clckwise_by_zip_method(matrix):
    return list(list(x)[::-1] for x in zip(*matrix))

#solution1 #解决方案1

print(list(list(x) for x in zip(*m))[::-1])

#solution2 #解决方案2

print([[x[i] for x in m] for i in range(len(m))][::-1])

#solution3 #解决方案3

r = []
i = 0
for row in m:
  listToAdd = [item[i] for item in m]
  r.append(listToAdd)
  i +=1
print(r[::-1])

Look at this code.看看这段代码。 This is the way to rotate any matrix by 90 degrees using scratch这是使用从头开始将任何矩阵旋转 90 度的方法

[This is the code to have a matrix rotated by 90 degrees][1] [这是将矩阵旋转 90 度的代码][1]

    n = input("enter input:")
    l =[]

    while (n !=""):
    
        l.append(n.split(" "))
        n = input("enter input:")
        l1=[]
    for i in range(len(l[0])):
        l1.append([])
    for j in range (len(l1)):
        for p in range(len(l)):
           l1[j].append(l[p][-(j+1)])

    for s in l1:
         print(*s)
'''


  [1]: https://i.stack.imgur.com/c8jHC.png

Just flip the matrix vertically, then switch the upper-right triangle with the lower-left triangle只需垂直翻转矩阵,然后将右上三角形与左下三角形切换

def rotate_matrix_ccw(mat):
    if mat is None:
        return None
    n = len(mat)
    if n == 1:
        return mat
    for i in range(n):
        if len(mat[i]) != n:
            raise Exception("Matrix must be square")
    # flip the matrix vertically
    for j in range(n // 2):
        for i in range(n):
            mat[i][j], mat[i][n - 1 - j] = mat[i][n - 1 - j], mat[i][j]
    # switch the upper-right triangle with the lower-left triangle
    for i in range(n):
        for j in range(i):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
    return mat

You can loop through the original matrix and create a new one.您可以遍历原始矩阵并创建一个新矩阵。 This is my approach for counterclockwise, for the other way it would be similar.这是我逆时针的方法,否则它会相似。 This doesn't require it to be a square.这并不要求它是正方形。

def left_rotate(mat):
    if not mat: return []
    colcount = len(mat[0])

    # Initialize empty lists
    new = [list() for _ in range(colcount)]
    # Go through the rows, append elements one by one
    for row in mat:
        for j in range(colcount):
            new[j].append(row[colcount - 1 - j])
    return new

Example:例子:

>>> print(left_rotate([[1, 2], [3, 4], [5, 6]]))
[[2, 4, 6], [1, 3, 5]]

flip vertically (left to right) then transpose:垂直翻转(从左到右)然后转置:

m = [[1,2,3],
     [2,3,3],
     [5,4,3]]
print([list(x) for x in zip(*[x[::-1] for x in m])])
def rotateMatrix(self, matrix):
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    matrix.reverse()

Rotate matrix anti-clockwise 90deg (In-place)逆时针旋转矩阵 90 度(就地)

def rotate(matrix):
    for i in range(len(matrix) - 1, -1, -1):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    matrix.reverse()

Rotate matrix clockwise 90deg (In-place)将矩阵顺时针旋转 90 度(就地)

def rotate(matrix):
    matrix.reverse()
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

In case you're working with square matrixes (rows == cols) then you can use this:如果您正在使用方矩阵(行 == 列),那么您可以使用它:

list(zip(*reversed(a))) # 90 degrees clockwise
list(zip(*reversed(a)))[::-1] # 90 degrees counter-clockwise
def rotated_array(array):
    new_array = np.zeros([array.shape[0], array.shape[1]])
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            t = array.shape[0]-j-1          # To Start with last row and first column
            new_array[i, j] = array[t, i]
    return new_array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM