Rotating a two-dimensional array in Python
Consider the following two-dimensional list:
original = [[1, 2],
[3, 4]]
Lets break it down step by step:>>> original[::-1] # elements of original are reversed
[[3, 4], [1, 2]]
This list is passed into zip()
using argument unpacking, so the zip
call ends up being the equivalent of this:zip([3, 4],
[1, 2])
# ^ ^----column 2
# |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise
Hopefully the comments make it clear what zip
does, it will group elements from each input iterable based on index, or in other words it groups the columns. How do you rotate a two dimensional array?
Here it is in C#
int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};
int[,] rotated = RotateMatrix(array, 4);
static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}
return ret;
}
Problem with rotating a two-dimensional array in python
You can use zip
on the reversed array:
auxiliaryArray = list(zip(*multiarray[::-1]))
orauxiliaryArray = list(zip(*reversed(multiarray)))
output: [(7, 4, 1), (8, 5, 2), (9, 6, 3)]
If you need lists and not tuples:
auxiliaryArray = list(map(list, zip(*reversed(multiarray))))
output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
How do I rotate a 2-dimensional array in Python or how can I get the result below?
You can try:
>>> A=[[[0, 1, 2], [2, 0, 1], [1, 2, 0]],
... [[1, 0, 2], [0, 2, 1], [2, 1, 0]],
... [[1, 0, 2], [2, 1, 0], [0, 2, 1]]]
>>> transpose_data = map(list, zip(*A))
>>> for data in transpose_data:
... print(data)
...
[[0, 1, 2], [1, 0, 2], [1, 0, 2]]
[[2, 0, 1], [0, 2, 1], [2, 1, 0]]
[[1, 2, 0], [2, 1, 0], [0, 2, 1]]
How do you rotate a two dimensional array?
Here it is in C#
int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};
int[,] rotated = RotateMatrix(array, 4);
static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}
return ret;
}
Related Topics
Does 'Anaconda' Create a Separate Pythonpath Variable for Each New Environment
Scale Everything on Pygame Display Surface
Difference Between Variable and Get_Variable in Tensorflow
How to Detect If a File Is Binary (Non-Text) in Python
Is There a Function to Determine Which Quarter of the Year a Date Is In
Wrapping Around on a List When List Index Is Out of Range
Is 'Import Module' Better Coding Style Than 'From Module Import Function'
Pairwise Crossproduct in Python
"Overflowerror: Python Int Too Large to Convert to C Long" on Windows But Not MAC
Hide Chromedriver Console in Python
Does Python Do Slice-By-Reference on Strings
Rotating a Two-Dimensional Array in Python
How to Pipe Input to Python Line by Line from Linux Program
What Is the Default _Hash_ in Python