Dim*_*htz 1 python transpose numpy
当列表仅包含长度相同的行时,转置有效:
numpy.array([[1, 2], [3, 4]]).T.tolist();
>>> [[1, 3], [2, 4]]
Run Code Online (Sandbox Code Playgroud)
但是,在我的情况下,列表包含不同长度的行:
numpy.array([[1, 2, 3], [4, 5]]).T.tolist();
Run Code Online (Sandbox Code Playgroud)
哪个失败了.任何可能的解决方
如果您没有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]]
Run Code Online (Sandbox Code Playgroud)
zip_longest
None
由于不匹配的长度填充结果,因此列表理解并filter(None, ...)
用于删除None
值
在python 2.x中它会是 itertools.izip_longest