矩阵的原位旋转 [英] Inplace rotation of a matrix

查看:80
本文介绍了矩阵的原位旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表(我在这里称为矩阵),我想就地顺时针旋转90(即,不应对另一个矩阵).我想出了以下代码.

I have a list of lists (which I am calling here matrix), that I want to rotate by 90 clockwise in-place (i.e., without coping into another matrix). I came up with the following code.

我对算法本身感兴趣,使用纯Python(无需使用numpy进行转置).

I am interested in the algorithm itself, in a pure python (without transposing using numpy or so).

def rotate(M):
    n = len(M)
    m = len(M[0])

    for i in range(n//2):
        for j in range(i, m-1-i):
            ii, jj = i, j
            v0 = M[ii][jj]
            for _ in range(3):
                M[ii][jj] = M[n-1-jj][ii]
                ii, jj = n-1-jj, ii
            M[ii][jj] = v0

    return M

它很好用,但仅当行数等于列数时才有效.有什么想法可以修改我的函数以处理行数和列数不相等的情况?

It works well but only when the number of lines is equal to the number of columns. Any ideas for modifying my function to handle the case where the number of lines and columns are not equal ?

这里是一个例子:

input:      [[1, 2, 3, 4, 5],
            [6, 7, 8, 9, 10],
            [11, 12, 13, 14, 15],
            [16, 17, 18, 19, 20],
            [21, 22, 23, 24, 25]]

output      [[21, 16, 11, 6, 1],
            [22, 17, 12, 7, 2],
            [23, 18, 13, 8, 3],
            [24, 19, 14, 9, 4],
            [25, 20, 15, 10, 5]]

推荐答案

始终将numpy用于矩阵运算.我假设m*n numpy数组arr.我首先使用 np.transpose 进行了转置函数,然后使用 np.fliplr 功能.

Always use numpy for matrix operations. I'll assume an m*n numpy array arr. I first did a transpose using the np.transpose function and then I flipped it using the np.fliplr function.

output = np.fliplr(np.transpose(arr))


如评论中所述,如果没有用于矩形矩阵的临时变量,就无法进行就地替换.最好使用这样的函数来模拟行为(如果您担心存储问题),


As mentioned in the comments, there is no way to do an in-place replace without a temporary variable for rectangular matrices. It's better to simulate the behavior (if storage is your concern) using a function like this,

def clockwise(matrix, row, column):
    return matrix[-(column + 1)][row]

这篇关于矩阵的原位旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆