Python转置问题 [英] Python transpose problem

查看:123
本文介绍了Python转置问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

二维矩阵可以用Python逐行表示,作为列表列表:每个内部列表代表矩阵的一行。例如,矩阵



1 2 3

4 5 6

将表示为[[1 ,2,3],[4,5,6]]。



矩阵的转置使每一行成为一列。例如,上面矩阵的转置是



1 4

2 5

3 6 br />
写一个Python函数transpose(m),它使用这个逐行表示作为输入一个二维矩阵,并使用相同的表示返回矩阵的转置。



以下是一些示例,说明您的函数应该如何工作。您可以假设函数的输入始终是非空矩阵。



>>>转置([[1,4,9]])

[[1],[4],[9]]



> ;>>转置([[1,3,5],[2,4,6]])

[[1,2],[3,4],[5,6]]


我尝试过:



导入数学

def转置(m):

result = [[m [j] [i]对于范围内的j(len(m))]对于i在范围内(len(m [0]) )]
结果为


print(r)

A two dimensional matrix can be represented in Python row-wise, as a list of lists: each inner list represents one row of the matrix. For instance, the matrix

1 2 3
4 5 6
would be represented as [[1, 2, 3], [4, 5, 6]].

The transpose of a matrix makes each row into a column. For instance, the transpose of the matrix above is

1 4
2 5
3 6
Write a Python function transpose(m) that takes as input a two dimensional matrix using this row-wise representation and returns the transpose of the matrix using the same representation.

Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

>>> transpose([[1,4,9]])
[[1], [4], [9]]

>>> transpose([[1,3,5],[2,4,6]])
[[1, 2], [3, 4], [5, 6]]

What I have tried:

import math
def transpose(m):
result=[[[m[j][i] for j in range (len(m))] for i in range (len(m[0]))]
for r in result:
print(r)

推荐答案

result=[[m[j][i] for j in range (len(m))] for i in range (len(m[0]))]

这篇关于Python转置问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆