[Python]Double-level for loop

Matrix transpose

list01 = [
    [2, 4, 1, 8, 9],
    [1, 2, 3, 8, 9],
    [8, 9, 10, 8, 9],
    [8, 9, 10, 8, 9]
]

list02 = []

for r in range(len(list01[0])):
    line = []
    for c in range(len(list01)):
        line.append(list01[c][r])
    list02.append(line)

Another algorithm for matrix transposition:

Using the diagonal as the dividing line, just swap the elements in the lower half of the diagonal with the elements in the upper half.

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

for r in range(len(list01)):
    # function 1:
    # for c in range(len(list01)):
    #     if r < c:
    #         list01[r][c], list01[c][r] = list01[c][r], list01[r][c]
    
    # function 2
    for c in range(r, len(list01)):
        list01[r][c], list01[c][r] = list01[c][r], list01[r][c]

print(list01)

output

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

Guess you like

Origin blog.csdn.net/x1987200567/article/details/126876461