[Python]双层for 循环

矩阵转置

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)

矩阵转置的另外一种算法:

以对角线为分割线,讲对角线下半部分的元素与上半部分的元素交换位置即可

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)

输出

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

猜你喜欢

转载自blog.csdn.net/x1987200567/article/details/126876461