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)
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; returned everything in groups of 3. And they were in the wrong order as well.
CodePudding user response:
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))
CodePudding user response:
Can use np.swapaxes(a, 1, 2)
https://numpy.org/doc/stable/reference/generated/numpy.swapaxes.html
This also works on lists, not just numpy arrays.
CodePudding user response:
Other answers touched on the relevant numpy method. Here is a list comprehension (just for fun) to obtain the same result as np.swapaxes(lst, 1, 2)
:
out = [[[row[i] for row in l] for i in range(len(l))] for l in my_list]
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]]]