How To Transpose A 2d List Array Using Loops In Python?
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 t
Solution 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.
Solution 2:
Here is a solution that is based on your code:
deftranspose(a):
s = []
# We need to assume that each inner list has the same size for this to work
size = len(a[0])
for col inrange(size):
inner = []
for row inrange(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]]
Solution 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 inrange(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)]
Post a Comment for "How To Transpose A 2d List Array Using Loops In Python?"