Python中的基本矩阵转置

时间:2019-07-09 13:21:54

标签: python list matrix transpose

我尝试了使用python进行矩阵转置的最基本方法。但是,我没有得到所需的结果。以下是代码:

A = [ [1, 1, 1, 1], 
    [2, 2, 2, 2], 
    [3, 3, 3, 3], 
    [4, 4, 4, 4]] 

#print (A)
def TS (A):
    B = A
    for i in (range(len(A))):
        for j in (range(len(A))):
            A[i][j] = B [j][i]
TS(A)
#print (A)

for i in range(len(A)): 
    for j in range(len(A)): 
        print(B[i][j], " ", end='') 
    print() 

这是我得到的结果:

1  2  3  4  
2  2  3  4  
3  3  3  4  
4  4  4  4  

5 个答案:

答案 0 :(得分:1)

为什么不尝试numpy :)

import numpy as np
z = np.transpose(np.array(A))

答案 1 :(得分:1)

vendor

输出

结果矩阵为

A = [ [1, 1, 1, 1], 
    [2, 2, 2, 2], 
    [3, 3, 3, 3], 
    [4, 4, 4, 4]]

def transpose(A,B): 

    for i in range(len(A)): 
        for j in range(len(A)): 
            B[i][j] = A[j][i]    

B = [[0 for x in range(len(A))] for y in range(len(A))]  

transpose(A, B) 

print("Result matrix is") 
for i in range(len(A)): 
    for j in range(len(A)): 
        print(B[i][j], " ", end='') 
    print() 

答案 2 :(得分:1)

您的问题有两个:

1- B是矩阵A的标记,即对A的每个修饰,也对B进行了修饰
2- B在转置功能中是本地的,无法在外部访问

A = [[1, 1, 1, 1], 
     [2, 2, 2, 2], 
     [3, 3, 3, 3], 
     [4, 4, 4, 4]] 

def TS (A):
    B = [row[:] for row in A]   # make a copy of A, not assigning a new label on it.
    for i in (range(len(A))):
        for j in (range(len(A))):
            B[i][j] = A[j][i]
    return B

B = TS(A)

for i in range(len(A)): 
    for j in range(len(A)): 
        print(B[i][j], " ", end='') 
    print() 

输出:

1  2  3  4  
1  2  3  4  
1  2  3  4  
1  2  3  4 

答案 3 :(得分:1)

使用深度复制将A复制到B,则应该为B [i] [j] = A [j] [i]。必须是拼写错误。

A = [[1, 1, 1, 1], 
    [2, 2, 2, 2], 
    [3, 3, 3, 3], 
    [4, 4, 4, 4]] 

#print (A)
def TS (A):
    from copy import deepcopy
    B = deepcopy(A)
    for i in (range(len(A))):
        for j in (range(len(A))):
            B[i][j] = A [j][i]
    return B
B = TS(A)
#print (len(A))

for i in range(len(B)): 
    for j in range(len(B)): 
        print(B[i][j], " ", end='') 
    print() 

结果:

1  2  3  4  
1  2  3  4  
1  2  3  4  
1  2  3  4 

答案 4 :(得分:0)

B是矩阵A上的标签,即对A的每次修改,也对B进行了修改。因此第二行的值错误。 为什么不这样尝试呢?

 A = [ [1, 1, 1, 1], 
 [2, 2, 2, 2], 
 [3, 3, 3, 3], 
 [4, 4, 4, 4]] 
 def TS(A):
    for i in range(len(A)): 
        for j in range(len(A)): 
            print(A[j][i], " ", end='') 
        print()        
 TS(A)