如何在Python 3中转置数组?

时间:2022-01-21 21:29:13

I've been scanning the forums and haven't found an answer yet that I can apply to my situation. I need to be able to take an n by n array and transpose it in Python-3. The example given is that I have this list input into the function:

我一直在扫描论坛,还没有找到答案,我可以适用于我的情况。我需要能够采用n×n数组并将其转换为Python-3。给出的例子是我将这个列表输入到函数中:

[[4, 2, 1], ["a", "a", "a"], [-1, -2, -3]] and it needs to be transposed to read:

[[4,2,1],[“a”,“a”,“a”],[-1,-2,-3]]需要转换为:

[[4, 'a', -1], [2, 'a', -2], [1, 'a', -3]] So basically reading vertically instead of horizontally.

[[4,'a', - 1],[2,'a', - 2],[1,'a', - 3]]所以基本上是垂直阅读而不是水平阅读。

I CANNOT use things like zip or numpy, I have to make my own function.

我不能使用拉链或凹凸不平的东西,我必须自己做功能。

Been rattling my brain at this for two nights and it's a huge headache. If anyone could help and then provide an explanation so I can learn it, I'd be grateful.

在这两天晚上我的大脑一直在喋喋不休,这是一个巨大的头痛。如果有人可以提供帮助,然后提供解释,以便我可以学习,我将不胜感激。

Edit:

编辑:

I should add for reference sake that the argument variable is M. The function we're supposed to write is trans(M):

我应该添加以供参考,参数变量是M.我们应该编写的函数是trans(M):

1 个解决方案

#1


1  

A one-liner:

单行:

def trans(M):
    return [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]

result:

结果:

>>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> trans(M)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]
# or for a non-square matrix:
>>> N = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> trans(N)
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

Additional Note: If you look up the tutorial on list comprehension, one of the examples is in fact transposition of a matrix array.

附加注意:如果您查看列表推导教程,其中一个示例实际上是矩阵数组的转置。

#1


1  

A one-liner:

单行:

def trans(M):
    return [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]

result:

结果:

>>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> trans(M)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]
# or for a non-square matrix:
>>> N = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> trans(N)
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

Additional Note: If you look up the tutorial on list comprehension, one of the examples is in fact transposition of a matrix array.

附加注意:如果您查看列表推导教程,其中一个示例实际上是矩阵数组的转置。