如何转置列表?

use*_*724 3 python transpose list matrix addition

假设我有一个列表[[1,2,3],[4,5,6]]

我如何转置它们,使它们成为:[[1, 4], [2, 5], [3, 6]]

我必须使用该zip功能吗?该zip功能是最简单的方法吗?

def m_transpose(m):
    trans = zip(m)
    return trans
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 5

使用zipand*splat是纯 Python 中最简单的方法。

>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]
Run Code Online (Sandbox Code Playgroud)

请注意,您在里面得到的是元组而不是列表。如果您需要列表,请使用map(list, zip(*l)).

如果您愿意使用numpy而不是列表列表,那么使用该.T属性甚至更容易:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]
Run Code Online (Sandbox Code Playgroud)