python - Reshape list of lists based on position of the element -
this question has answer here:
- transpose matrix in python [closed] 3 answers
i have list of lists looks this;
[[4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0]] which efficient way 3 lists above list based on position of element?
result:
[4,0,0,1,2] [0,0,1,1,0] [1,1,2,0,0]
you can use zip , list comprehension:
>>> lst = [[4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0]] >>> [list(x) x in zip(*lst)] [[4, 0, 0, 1, 2], [0, 0, 1, 1, 0], [1, 1, 2, 0, 0]] >>> placing * before lst unpacks list arguments zip function. in case:
zip(*lst) is equivalent writing:
zip([4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0]) zip zips these lists returning iterator of tuples n-th tuple contains n-th item each of lists. in case, returns:1
>>> list(zip(*lst)) [(4, 0, 0, 1, 2), (0, 0, 1, 1, 0), (1, 1, 2, 0, 0)] >>> finally, list comprehension converts these tuples lists , collects them new list.
1you need call list() on zip(*lst) view items because zip returns iterator in python 3.x.
Comments
Post a Comment