Python - 使用 numpy 转置列表(不同长度的行)失败

Python - Transposing a list (rows with different length) using numpy fails

当列表仅包含长度相同的行时,转置有效:

numpy.array([[1, 2], [3, 4]]).T.tolist();
>>> [[1, 3], [2, 4]]

但是,在我的例子中,列表包含不同长度的行:

numpy.array([[1, 2, 3], [4, 5]]).T.tolist();

失败了。任何可能的解决方案?

如果您没有 numpy 作为强制要求,您可以使用 itertools.zip_longest 进行转置:

from itertools import zip_longest

l = [[1, 2, 3], [4, 5]]
r = [list(filter(None,i)) for i in zip_longest(*l)]
print(r)
# [[1, 4], [2, 5], [3]]
由于 不匹配 长度,

zip_longestNone 填充结果,因此列表理解和 filter(None, ...) 用于删除 None

在 python 2.x 中会是 itertools.izip_longest

使用所有内置...

l = [[1, 2, 3], [4, 5]]
res = [[] for _ in range(max(len(sl) for sl in l))]

for sl in l:
    for x, res_sl in zip(sl, res):
        res_sl.append(x)