Day4 2D array rotation 90 degrees, day4 2D array 90 degrees
The rotation of a two-dimensional array is actually the reconciliation of elements in the array. There is a 4 × 4 two-dimensional array below, [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], it is now required to convert a two-dimensional array into the following form: [0, 0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3, 3]. Let's take a look at the flowchart below:
Flowchart:
As shown in the preceding figure, the flowchart is simple interchange. Here we use the code to implement row-and-column swaps:
Data = [[I for I in range (4)] for j in range (4)] print (data) # define the initial values of rows. We found that, the change of rows starts from 0 and increments to 3col = 0 while col <4: # The end condition of the loop. Because there are only four rows, so loop 4 ends for row in range (col, 4): # Here we increase the number of rows and columns by 1 in each loop, avoid Converting tem = data [row] [col] # storing temporary variables before conversion, otherwise, the value of data [row] [col] = data [col] [row] # the values of the columns in the list are interchangeable. data [col] [row] = tem col + = 1 # print (data) is added to the column index each time)
The theme of the above Code is the thought in the flowchart. You only need to perform the necessary conversion. Pay attention to the value changes during the conversion process. Therefore, the flowchart is very important.
Run the following code:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]
[[0, 0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3, 3]