[英]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.在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!
非常感谢!
>>> 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. zip(*a)
解包的三个子列表a
由元件和将它们组合的元素。 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.但是
zip()
在输出中返回元组而不是您想要的列表。 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. [list(x) for x in zip(*a)]
将每个元组转换为列表,以您需要的方式输出。
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]]
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()
:但是,最简单的方法是使用
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.