I want to use the double loop of the Python array list to come out vertically (column 4)

Asked 2 years ago, Updated 2 years ago, 39 views

The output result of the puzzle is

[[1,2,3,4], 
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]

I want to use a double loop to make it come out vertically (column 4) but I can't find an answer even if I think about it for hours. Masters, please help me.

The output should not come in a row.

puzzle = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
def puzzle_view(puzzle):
    puzzle_list = []
    for i in puzzle:
        for j in i:
            puzzle_list.append(j)
    return puzzle_list

python array

2022-09-21 10:42

1 Answers

Do I have to use a double loop?

The samples below are samples obtained using numpy and zip functions.

Add Double Loop

import numpy as np
puzzle = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
np.array(puzzle).T.tolist()
[[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]

list(zip(*puzzle))
[(1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15), (4, 8, 12, 16)]

result = [[], [], [], []]
for l in puzzle:
    for i, n in enumerate(l):
        result[i].append(n)
[[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]


2022-09-21 10:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.