Arrays 转置矩阵(python 3)
我用python编写了一个模块,用于输入一个如下所示的矩阵:Arrays 转置矩阵(python 3),arrays,python-3.x,matrix,module,transpose,Arrays,Python 3.x,Matrix,Module,Transpose,我用python编写了一个模块,用于输入一个如下所示的矩阵: matrix = [] loop = True while loop: line = input() if not line: #the way it works is that you enter value separated by a space and enter a blank line to finish inputing the matrix loop = False
matrix = []
loop = True
while loop:
line = input()
if not line: #the way it works is that you enter value separated by a space and enter a blank line to finish inputing the matrix
loop = False
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
print('\n'.join([' '.join(map(str, row)) for row in matrix]))
最后一行就是这样打印矩阵
1 2 3
4 5 6
我希望能够在另一个模块中转置矩阵,到目前为止我已经尝试过:
def transpose_matrix(matrix):
zip(*matrix)
return matrix
但它实际上不起作用,它对实际矩阵没有任何影响,矩阵保持不变,我不明白
谢谢 首先,我将通过以下方式获得矩阵,以避免最后出现空列表:
matrix = []
while True:
line = input()
if not line:
break
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
至于转置它,最好的办法是把它留给numpy:
import numpy as np
transposed_matrix = np.transpose(np.array(matrix))
如果出于任何原因,您希望避免numpy(这是不可取的),您可以使用:
transposed_matrix = []
for line in zip(*matrix):
transposed_matrix.append(line)