How do I transpose a List? [duplicate]

為{幸葍}努か 提交于 2019-12-17 20:54:56

问题


Let's say I have a SINGLE list [[1,2,3],[4,5,6]]

How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]?

Do I have to use the zip function? Is the zip function the easiest way?

def m_transpose(m):
    trans = zip(m)
    return trans

回答1:


Using zip and *splat is the easiest way in pure Python.

>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]

Note that you get tuples inside instead of lists. If you need the lists, use map(list, zip(*l)).

If you're open to using numpy instead of a list of lists, then using the .T attribute is even easier:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]



回答2:


You can use map with None as the first parameter:

>>> li=[[1,2,3],[4,5,6]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6)]

Unlike zip it works on uneven lists:

>>> li=[[1,2,3],[4,5,6,7]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6), (None, 7)]
>>> zip(*li)
[(1, 4), (2, 5), (3, 6)]
#                      ^^ 7 missing...

Then call map again with list as the first parameter if you want the sub elements to be lists instead of tuples:

>>> map(list, map(None, *li))
[[1, 4], [2, 5], [3, 6]]

(Note: the use of map with None to transpose a matrix is not supported in Python 3.x. Use zip_longest from itertools to get the same functionality...)




回答3:


zip() doesn't seem to do what you wanted, using zip() you get a list of tuples. This should work though:

>>> new_list = []
>>> old_list = [[1,2,3],[4,5,6]]
>>> for index in range(len(old_list[0])):
...     new_list.append([old_list[0][index], old_list[1][index]])
... 
>>> new_list
[[1, 4], [2, 5], [3, 6]]



回答4:


The exact way of use zip() and get what you want is:

>>> l = [[1,2,3],[4,5,6]]
>>> [list(x) for x in zip(*l)]
>>> [[1, 4], [2, 5], [3, 6]]

This code use list keyword for casting the tuples returned by zip into lists.



来源:https://stackoverflow.com/questions/23525451/how-do-i-transpose-a-list

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