Python - 使用 numpy 转置列表(具有不同长度的行)失败 [英] Python - Transposing a list (rows with different length) using numpy fails
问题描述
当列表只包含相同长度的行时,转置有效:
When the list contains only rows with same length the transposition works:
numpy.array([[1, 2], [3, 4]]).T.tolist();
>>> [[1, 3], [2, 4]]
但是,就我而言,列表包含不同长度的行:
But, in my case the list contains rows with different length:
numpy.array([[1, 2, 3], [4, 5]]).T.tolist();
失败了.任何可能的解决方案?
which fails. Any possible solution?
推荐答案
如果您没有将 numpy
作为强制性要求,您可以使用 itertools.zip_longest
进行转置:
If you're not having numpy
as a compulsory requirement, you can use itertools.zip_longest
to do the transpose:
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_longest
用None
填充结果,因此列表理解和filter(None, ...)
用于删除 None
值
zip_longest
pads the results with None
due to unmatching lengths, so the list comprehension and filter(None, ...)
is used to remove the None
values
在 python 2.x 中,它是 itertools.izip_longest
In python 2.x it would be itertools.izip_longest
这篇关于Python - 使用 numpy 转置列表(具有不同长度的行)失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!