1

Lets say I have a 9x9 2D array

testboard = [
    [7,8,0,4,0,0,1,2,0],
    [6,0,0,0,7,5,0,0,9],
    [0,0,0,6,0,1,0,7,8],
    [0,0,7,0,4,0,2,6,0],
    [0,0,1,0,5,0,9,3,0],
    [9,0,4,0,6,0,0,0,5],
    [0,7,0,3,0,0,0,1,2],
    [1,2,0,0,0,7,4,0,0],
    [0,4,9,2,0,6,0,0,7]
]

I can print the columns with this code:

for i in range(len(testboard)): 
    for j in range(len(testboard)):
        if j == 8: 
            print(str(testboard[j][i]))
        else:  
            print(str(testboard[j][i]) + ", ", end = "")
    

which prints this:

7,6,0,0,0,9,0,1,0
8,0,0,0,0,0,7,2,4
0,0,0,7,1,4,0,0,9
4,0,6,0,0,0,3,0,2
0,7,0,4,5,6,0,0,0
0,5,1,0,0,0,0,7,6
1,0,0,2,9,0,0,4,0
2,0,7,6,3,0,1,0,0
0,9,8,0,0,5,2,0,7

However, I would like to put these columns into a new array, of lists. How could I get these into a new array?

1
  • Google something like "Python transpose matrix" - flipping rows and columns is called "transposing the matrix" Commented Jan 6, 2021 at 19:01

3 Answers 3

1

You were pretty close with your printing, you just need to make a new list,

new = []
for i in range(len(testboard)):
    new.append([])
    for j in range(len(testboard)):
        new[i].append(testboard[j][i])
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thanks! The new[i] was the part that I was missing
0

Try something like testboard = [[testboard[j][i] for j in range(size)] for i in range(size)] to generate a new list where size is the length of the array (9 in your case).

Comments

0

I suppose you are trying to implement the transpose function from scratch; refraining from using numpy.

one way to do is to initialize another array with the shape of the transposed array.

transposed_array = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0]]

and then setting each 0 with its corresponding value in the loop:

for i in range(len(testboard)): 
    for j in range(len(testboard)):
        transposed_array[i][j] = testboard[j][i]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.