问题
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