转置方阵
l=[[1,2,3],[4,5,6],[7,8,9]] for i in range(3): for j in range(3): if i>j: l[i][j], l[j][i] = l[j][i], l[i][j] print(l)
对角线的一半与另一半交换位置
转置矩阵
l=[[1,2,3],[4,5,6]] n=[] for i in range(3): n.append([]) for j in range(2): n[i].append(0) for i in range(3): for j in range(2): n[i][j]=l[j][i] print(n)
将以上for循环写成列表解析式
l=[[1,2,3],[4,5,6]] n=[[0 for i in range(2)]for i in range(3)] for i in range(len(n)): for j in range(len(n[0])): n[i][j]=l[j][i] print(n)
解析式的输出为
n=[[0 for i in range(2)]for i in range(3)] n
[[0, 0], [0, 0], [0, 0]]