在Python快速矩阵转置 [英] Fast matrix transposition in Python

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

问题描述

有没有快速的方法来制作一个矩形的二维矩阵Python中的换位(非涉及任何库导入)。?

我说,如果我有一个数组

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

我需要一个数组Y,它应该是X的转版,所以

  Y = [1,4],
    〔2.5〕,
    [3,6]
 

解决方案

简单: Y = ZIP(* X)

 >>> X = [[1,2,3],[4,5,6]]
>>> Y = ZIP(* X)
>>> ÿ
[(1,4),(2,5),(3,6)]
 

编辑:来回答什么呢ZIP(* X)的意思,这里是蟒蛇人工为例意见的问题:

 >>>范围(3,6)#独立参数正常呼叫
[3,4,5]
>>>的args = [3,6]
>>>范围(*参数)与参数#打来的电话清单解压
[3,4,5]
 

所以,当 X [1,2,3],[4,5,6]] 压缩(* X)压缩([1,2,3],[4,5,6]),

Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?

Say, if I have an array

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

I need an array Y which should be a transposed version of X, so

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

解决方案

Simple: Y=zip(*X)

>>> X=[[1,2,3], [4,5,6]]
>>> Y=zip(*X)
>>> Y
[(1, 4), (2, 5), (3, 6)]

EDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

So, when X is [[1,2,3], [4,5,6]], zip(*X) is zip([1,2,3], [4,5,6])

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

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