Python 中的矩阵转置

我正在尝试为 python 创建一个矩阵转置函数,但似乎无法实现。 就算我有

theArray = [['a','b','c'],['d','e','f'],['g','h','i']]

我想要我的函数

newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]

换句话说,如果我把这个二维数组打印成列和行,我希望这些行变成列,列变成行。

我做了这个,但是没有用

def matrixTranspose(anArray):
transposed = [None]*len(anArray[0])
for t in range(len(anArray)):
for tt in range(len(anArray[t])):
transposed[t] = [None]*len(anArray)
transposed[t][tt] = anArray[tt][t]
print transposed
171493 次浏览

巨蟒2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

巨蟒3:

>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

原始代码的问题在于,您在每个元素上初始化了 transpose[t],而不是每行只初始化一次:

def matrixTranspose(anArray):
transposed = [None]*len(anArray[0])
for t in range(len(anArray)):
transposed[t] = [None]*len(anArray)
for tt in range(len(anArray[t])):
transposed[t][tt] = anArray[tt][t]
print transposed

这是可行的,尽管有更多的 Python 方法来完成同样的事情,包括@J. F. 的 zip应用程序。

def matrixTranspose(anArray):
transposed = [None]*len(anArray[0])


for i in range(len(transposed)):
transposed[i] = [None]*len(transposed)


for t in range(len(anArray)):
for tt in range(len(anArray[t])):
transposed[t][tt] = anArray[tt][t]
return transposed


theArray = [['a','b','c'],['d','e','f'],['g','h','i']]


print matrixTranspose(theArray)

如果你的行不相等,你也可以使用 map:

>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> map(None,*uneven)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

编辑: 在 Python 3中,map的功能发生了变化,可以使用 itertools.zip_longest代替:
来源: < a href = “ http://docs.Python.org/3/whatsnew/3.0.html # views-and-iterators-inib-of-ists”rel = “ noReferrer”> What’s New In Python 3.0

>>> import itertools
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> list(itertools.zip_longest(*uneven))
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

要完成 J.F. 塞巴斯蒂安的回答,如果你有一个不同长度的列表,请查看 这个来自 ActiveState 的很棒的帖子。简而言之:

内置函数 zip 执行类似的工作,但是将结果截断 到最短列表的长度,所以从原来的一些元素 资料可能会在事后遗失。

要处理不同长度的列表列表,请使用:

def transposed(lists):
if not lists: return []
return map(lambda *row: list(row), *lists)


def transposed2(lists, defval=0):
if not lists: return []
return map(lambda *row: [elem or defval for elem in row], *lists)
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> [list(i) for i in zip(*theArray)]
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]

列表生成器使用列表项而不是元组创建一个新的2d 数组。

“最佳”答案已经提交了,但是我想补充一点,您可以使用嵌套的列表理解,正如在 Python 教程中看到的那样。

下面是如何得到一个换位数组:

def matrixTranspose( matrix ):
if not matrix: return []
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
matrix.append([])
for j in range(n):
elem=input('enter element: ')
matrix[i].append(elem)


#print matrix
for i in range(m):
for j in range(n):
print matrix[i][j],
print '\n'


#generate transpose
transpose=[]
for j in range(n):
transpose.append([])
for i in range (m):
ent=matrix[i][j]
transpose[j].append(ent)


#print transpose
for i in range (n):
for j in range (m):
print transpose[i][j],
print '\n'

麻木的时候就容易多了:

>>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr.T
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
>>> theArray
array([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']],
dtype='|S1')
>>> theArray.T
array([['a', 'd', 'g'],
['b', 'e', 'h'],
['c', 'f', 'i']],
dtype='|S1')
a=[]
def showmatrix (a,m,n):
for i in range (m):
for j in range (n):
k=int(input("enter the number")
a.append(k)
print (a[i][j]),


print('\t')




def showtranspose(a,m,n):
for j in range(n):
for i in range(m):
print(a[i][j]),
print('\t')


a=((89,45,50),(130,120,40),(69,79,57),(78,4,8))
print("given matrix of order 4x3 is :")
showmatrix(a,4,3)




print("Transpose matrix is:")
showtranspose(a,4,3)

这一个将保持矩形的形状,以便后续的转置将得到正确的结果:

import itertools
def transpose(list_of_lists):
return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))
def transpose(matrix):
x=0
trans=[]
b=len(matrix[0])
while b!=0:
trans.append([])
b-=1
for list in matrix:
for element in list:
trans[x].append(element)
x+=1
x=0
return trans
def transpose(matrix):
listOfLists = []
for row in range(len(matrix[0])):
colList = []
for col in range(len(matrix)):
colList.append(matrix[col][row])
listOfLists.append(colList)


return listOfLists

`

def transpose(m):
return(list(map(list,list(zip(*m)))))

这个函数将返回调位

转换矩阵的 Python 程序:

row,col = map(int,input().split())
matrix = list()


for i in range(row):
r = list(map(int,input().split()))
matrix.append(r)


trans = [[0 for y in range(row)]for x in range(col)]


for i in range(len(matrix[0])):
for j in range(len(matrix)):
trans[i][j] = matrix[j][i]


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

如果你想转置一个矩阵,比如 A = np.array ([[1,2] ,[3,4]]) ,那么你可以简单地使用 A.T,但是对于一个向量,比如 a = [1,2] ,a.T 不会返回一个转置!你需要使用 a.reform (- 1,1) ,如下所示

import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))


A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)

您可以简单地使用 Python 理解来完成。

arr = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
]
transpose = [[arr[y][x] for y in range(len(arr))] for x in range(len(arr[0]))]

你可以试试下面的列表内涵

矩阵 = [[‘ a’,‘ b’,‘ c’] ,[‘ d’,‘ e’,‘ f’] ,[‘ g’,‘ h’,‘ i’]] N = len (矩阵) 转置 = [[ row [ i ]表示矩阵中的行]表示范围(n)中的 i ] 打印(转换)

import  numpy as np #Import Numpy


m=int(input("Enter row")) #Input Number of row


n=int(input("Enter column")) #Input number of column


a=[] #Blank Matrix


for i in range(m): #Row Input


b=[] #Blank List


for j in range(n):#column Input


j=int(input("Enter Number in Pocket ["+str(i)+"]["+str(j)+"]")) #sow Row Column Number


b.append(j) #addVlaue to list


a.append(b)#Add List To Matrix


a=np.array(a)#convert 1matrix as Numpy


b=a.transpose()#transpose Using Numpy


print(a) #Print Matrix


print(b)#print Transpose Matrix