Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Trying to flip columns and rows in an array in python. I can print them, but not sure how make them into a new array

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...