简体   繁体   English

如何转置 3d/2d 列表?

[英]How to transpose a 3d/2d list?

This is my list:这是我的清单:

[[[22, 13, 17, 11,  0],
[8,  2, 23,  4, 24],
[21,  9, 14, 16,  7],
[6, 10,  3, 18,  5],
[1, 12, 20, 15, 19]],

[[3, 15,  0,  2, 22],
[9, 18, 13, 17,  5],
[19,  8,  7, 25, 23],
[20, 11, 10, 24,  4],
[14, 21, 16, 12,  6]],

[[14, 21, 17, 24,  4],
[10, 16, 15,  9, 19],
[18,  8, 23, 26, 20],
[22, 11, 13,  6,  5],
[2,  0, 12,  3,  7]]]

The transposed list that I want is this:我想要的转置列表是这样的:

[[[22,  8, 21,  6,  1],
[13,  2,  9,  10, 12],
[17,  23, 14,  3, 20],
[11,  4,  16, 18, 15],
[0, 24,  7,  5, 19]],

[[3, 9,  19,  20, 14],
[15, 18,  8, 11, 21],
[0,  13,  7, 10, 16],
[2, 11, 10, 24,  12],
[22, 21, 16,  4,  6]],

[[14, 10, 18, 22,  2],
[21, 16,  8,  11, 0],
[17,  15, 23, 13, 12],
[24,  9, 26,  6,  3],
[4,  19, 20,  5,  7]]]

How would I do that?我该怎么做? Any help would be appreciated (Not sure if this is a 3d list or a 2d list)任何帮助将不胜感激(不确定这是 3d 列表还是 2d 列表)

Each list item is separated by a blank line, I will refer to this as a group(of 5 since each group has 5 different lists in it) I tried using Numpy's transpose, arange, etc. However upon using Numpy's transpose, arange, etc;每个列表项由一个空行分隔,我将其称为一个组(5 个,因为每个组中有 5 个不同的列表)我尝试使用 Numpy 的转置、arange 等。但是在使用 Numpy 的转置、arange 等; returned everything in groups of 3. And they were in the wrong order as well.以 3 个一组的形式返回所有内容。而且它们的顺序也错误。

Just switch the 1st and 2nd axes around:只需切换第一和第二轴:

import numpy as np

a = np.array(
[[[22, 13, 17, 11,  0],
[8,  2, 23,  4, 24],
[21,  9, 14, 16,  7],
[6, 10,  3, 18,  5],
[1, 12, 20, 15, 19]],
[[3, 15,  0,  2, 22],
[9, 18, 13, 17,  5],
[19,  8,  7, 25, 23],
[20, 11, 10, 24,  4],
[14, 21, 16, 12,  6]],

[[14, 21, 17, 24,  4],
[10, 16, 15,  9, 19],
[18,  8, 23, 26, 20],
[22, 11, 13,  6,  5],
[2,  0, 12,  3,  7]]])

print(np.swapaxes(a, 1, 2))

Can use np.swapaxes(a, 1, 2)可以使用np.swapaxes(a, 1, 2)

https://numpy.org/doc/stable/reference/generated/numpy.swapaxes.html https://numpy.org/doc/stable/reference/generated/numpy.swapaxes.html

This also works on lists, not just numpy arrays.这也适用于列表,而不仅仅是 numpy arrays。

Other answers touched on the relevant numpy method.其他答案涉及相关的 numpy 方法。 Here is a list comprehension (just for fun) to obtain the same result as np.swapaxes(lst, 1, 2) :这是一个列表理解(只是为了好玩)以获得与np.swapaxes(lst, 1, 2)相同的结果:

out = [[[row[i] for row in l] for i in range(len(l))] for l in my_list]

Output: Output:

[[[22, 8, 21, 6, 1],
  [13, 2, 9, 10, 12],
  [17, 23, 14, 3, 20],
  [11, 4, 16, 18, 15],
  [0, 24, 7, 5, 19]],
 [[3, 9, 19, 20, 14],
  [15, 18, 8, 11, 21],
  [0, 13, 7, 10, 16],
  [2, 17, 25, 24, 12],
  [22, 5, 23, 4, 6]],
 [[14, 10, 18, 22, 2],
  [21, 16, 8, 11, 0],
  [17, 15, 23, 13, 12],
  [24, 9, 26, 6, 3],
  [4, 19, 20, 5, 7]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM