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

扶醉桌前 提交于 2019-12-11 13:36:12

问题


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?


回答1:


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 pads the results with None due to unmatching lengths, so the list comprehension and filter(None, ...) is used to remove the None values

In python 2.x it would be itertools.izip_longest




回答2:


Using all builtins...

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)


来源:https://stackoverflow.com/questions/38466460/python-transposing-a-list-rows-with-different-length-using-numpy-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!