How to transpose a 2D list array using loops in python?

大兔子大兔子 提交于 2021-01-28 21:06:58

问题


Say I have:

a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]

and I want to transpose it to:

a = [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

using loops in python. The current code that I have is:

def transpose(a):
    s = []
    for row in range(len(a)):
        for col in range(len(a)):
            s = s + [a[col][row]]
return s

But this gives me the output of:

[1, 0, 4, 1, 2, 0, 1, -1, 10]

Instead of this:

[[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

Can anyone help me? I'm still new at this stuff and don't understand why it doesn't work. Thanks so much!


回答1:


Use zip()

>>> a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]
>>> [list(x) for x in zip(*a)]
[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

zip(*a) unpacks the three sub-lists in a and combines them element by element. Meaning, the first elements of the each of the three sub-lists are combined together, the second elements are combined together and so on. But zip() returns tuples instead of lists like you want in your output. Like this:

>>> zip(*a)
[(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)]

[list(x) for x in zip(*a)] converts each of the tuples to lists giving the output the way you need it.




回答2:


Here is a solution that is based on your code:

def transpose(a):
    s = []
    # We need to assume that each inner list has the same size for this to work
    size = len(a[0])
    for col in range(size):
        inner = []
        for row in range(len(a)):
            inner.append(a[row][col])
        s.append(inner)
    return s

If you define an inner list for the inner loop, your output is this:

[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]



回答3:


If you are looking for a solution without any fancy function. You may achieve it using list comprehension as:

>>> a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]
>>> sublist_size = len(a[0])
>>> [[item[i] for item in a] for i in range(sublist_size)]
[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

However, simplest way is by using zip():

>>> list(zip(*a))  # for Python 3, OR, just zip(*a) in Python 2 
[(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)]


来源:https://stackoverflow.com/questions/40442637/how-to-transpose-a-2d-list-array-using-loops-in-python

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