关于列表:Python中的Matrix Transpose

Matrix Transpose in Python

我正在尝试为python创建一个矩阵转置函数,但我似乎无法使它工作。说我有

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

我想让我的功能

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

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

我到目前为止做的,但不起作用

1
2
3
4
5
6
7
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

Python 2: </P >

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

Python 3: </P >

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


1
2
3
>>> 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']]

《战略,创建一个新的发电机的二维数组,而不是战略与项目部元组。 </P >


如果你是平等的Rows注释你可以也使用map: </P >

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

编辑:Python 3部《functionality mapitertools.zip_longest不能变,要使用的吧: 源:我国新的Python 3.0 </P >

1
2
3
4
>>> 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')]


多easier与numpy: </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> 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')

塞巴斯蒂安-完整的答案,如果你有一个列表,列表与不同的lengths,结帐后activestate这伟大的虔诚。在短: </P >

The built-in function zip does a similar job, but truncates the result
to the length of the shortest list, so some elements from the original
data may be lost afterwards.

to handle的列表,列表与不同的lengths,使用: </P >

1
2
3
4
5
6
7
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)


这个问题与你的原代码,是你,这initialized transpose[t]在每一个元素,而正是一次,当前每行: </P >

1
2
3
4
5
6
7
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

本厂,虽然有更多的语言方式,是对accomplish一样的东西,包括zipJ.F."的应用。 </P >


"野兽"的答案就已被submitted思想,但会增加,你可以用套式战略的理解,我看到的tutorial Python。 </P >

你怎么在这里的冰可以把一transposed阵列: </P >

1
2
3
def matrixTranspose( matrix ):
    if not matrix: return []
    return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]

这一意志preserve直角形,所以这是transposes将山羊后的结果:右击 </P >

1
2
3
import itertools
def transpose(list_of_lists):
  return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

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
26
27
28
29
30
31
#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 '
'


#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 '
'

Python程序到transpose矩阵: </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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(' ')


" </P >

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

</P >

"这个函数将返回的transpose </P >


1
2
3
4
5
6
7
8
9
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


1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)