Python 矩阵顺时针旋转90度

Python 矩阵顺时针旋转90度,python,python-3.x,Python,Python 3.x,我在解决一个矩阵旋转90度的问题。在这个问题中,我使用了一个列表k,其中填充了用户传递的精确度数的0 我尝试了以下代码: def rotate(m): k=[] f=[] print(m) for i in range(0,len(m)): f.append(0) for i in range(0,len(m)): k.append(f) print(k) for i in range(0,len(m)):

我在解决一个矩阵旋转90度的问题。在这个问题中,我使用了一个列表
k
,其中填充了用户传递的精确度数的0

我尝试了以下代码:

def rotate(m):
    k=[]
    f=[]
    print(m)
    for i in range(0,len(m)):
        f.append(0)
    for i in range(0,len(m)):
        k.append(f)
    print(k)
    for i in range(0,len(m)):
        for j in range(0,len(m)):
            print("REPLACING POSITION:",i,j )
            t=m[i][j]
            k[j][len(m)-i-1]=t
    return (k)
print(rotate([[1,2],[3,4]]))
我预计产出:

[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[3, 1], [4, 2]]
[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[4, 2], [4, 2]]
我得到了输出:

[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[3, 1], [4, 2]]
[[1, 2], [3, 4]]
[[0, 0], [0, 0]]
REPLACING POSITION: 0 0
REPLACING POSITION: 0 1
REPLACING POSITION: 1 0
REPLACING POSITION: 1 1
[[4, 2], [4, 2]]

为什么最后一行不断重复?请帮助。

您的第一个循环将生成列表
f
。 您的下一个for循环生成列表
k
,它意味着包含列表
f
len(m)
副本。问题是
f
(大多数列表)只是指针。所以list
k
实际上是指向同一个list
f
的指针列表

因此,对k中f的元素所做的所有修改都是对同一个列表进行的

一种解决方案是在使用slice操作符生成list
k
时使用list
f
的副本:

    for i in range(0,len(m)):
        k.append(f[:])
使用f.copy()获取列表的深度副本

    def rotate(m):
    k=[]
    f=[]
    print(m)
    for _ in range(0,len(m)):
        f.append(0)
    for _ in range(0,len(m)):
        k.append(f.copy())
    for i in range(0,len(m)):
        for j in range(0,len(m)):
            print("REPLACING POSITION:",i,j )
            t=m[i][j]
            k[j][len(m)-i-1]=t

            print(j,len(m)-i-1)           
    return k


print(rotate([[1,2],[3,4]]))