Home > Software engineering >  Is there a better way to write this nested for loop?
Is there a better way to write this nested for loop?

Time:12-05

I am trying to write a for loop which takes the contents of a 2D matrix and rotates them 90 degrees to the write like so:

|2|3|4|5|
---------
|7|6|8|9|

to:

|7|2|
-----
|6|3|
-----
|8|4|
-----
|9|5|

my code so far is:

rotated = []

# append a new matrix for each col      
for i in range(len(matrix[0])):
    rotated.append([])
    # append the last up till the 1st item to the 1st list in our new rotated list
    for j in range(len(matrix) - 1, -1, -1):
        rotated[i].append(matrix[j][i])
print(rotate)

CodePudding user response:

This is probably cheating, but.. it works ;)

arr = [
    [2, 3, 4, 5],
    [7, 6, 8, 9]
]

rotated = [ list(values) for values in zip(*reversed(arr)) ]
print(rotated)

CodePudding user response:

If it's a numpy array, you can change the order of the rows and transpose it:

arr = np.array([[2,3,4,5],[7,6,8,9]])
arr[[1,0]].T

Output:

[[7 2]
 [6 3]
 [8 4]
 [9 5]]
  • Related