Python 中的快速矩阵转置

发布于 2024-09-03 16:37:14 字数 217 浏览 1 评论 0原文

有没有快速的方法可以在Python中对矩形二维矩阵进行转置(不涉及任何库导入)?

比如说,如果我有一个数组,

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

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

Y=[ [1,4],
    [2,5],
    [3,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] ] 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

戒ㄋ 2024-09-10 16:37:14

Y=zip(*X)

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

编辑: 要回答评论中有关 zip(*X) 含义的问题,这里是 python 手册中的一个示例:

>>> 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]

简单 ,当 X[[1,2,3], [4,5,6]] 时,zip(*X) 为 <代码>zip([1,2,3],[4,5,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])

廻憶裏菂餘溫 2024-09-10 16:37:14
>>> X = [1,2,3], [4,5,6]]
>>> zip(*X)
[(1,4), (2,5), (3,6)]
>>> [list(tup) for tup in zip(*X)]
[[1,4], [2,5], [3,6]]

如果内部对绝对需要列表,请选择第二对。

>>> X = [1,2,3], [4,5,6]]
>>> zip(*X)
[(1,4), (2,5), (3,6)]
>>> [list(tup) for tup in zip(*X)]
[[1,4], [2,5], [3,6]]

If the inner pairs absolutely need to be lists, go with the second.

老街孤人 2024-09-10 16:37:14

如果您正在使用矩阵,那么您几乎肯定应该使用 numpy。这将比纯 Python 代码更容易、更高效地执行数值运算。

>>> x = [[1,2,3], [4,5,6]]
>>> x = numpy.array(x)
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x.T
array([[1, 4],
       [2, 5],
       [3, 6]])

“不涉及任何库导入”是一个愚蠢的、非生产性的要求。

If you're working with matrices, you should almost certainly be using numpy. This will perform numerical operations easier and more efficiently than pure Python code.

>>> x = [[1,2,3], [4,5,6]]
>>> x = numpy.array(x)
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x.T
array([[1, 4],
       [2, 5],
       [3, 6]])

"non-involving any library import" is a silly, non-productive requirement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文