Python中的快速矩阵转置 [英] Fast matrix transposition in Python
本文介绍了Python中的快速矩阵转置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何快速方法可以在 Python 中对矩形 2D 矩阵进行转置(不涉及任何库导入).?
说,如果我有一个数组
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) 是什么意思的问题,这里是 Python 手册中的一个示例:
<预><代码>>>>range(3, 6) # 带有单独参数的普通调用[3, 4, 5]>>>参数 = [3, 6]>>>range(*args) # 使用从列表中解压出来的参数调用[3, 4, 5]所以,当 X
是 [[1,2,3], [4,5,6]]
, zip(*X)
是 zip([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屋!
查看全文