a=[[1,2,3],[4,5,6],[7,8,9]]
1 2 3
4 5 6
7 8 9
转为:
1 4 7
2 5 8
3 6 9
[ [j[i] for j in a] for i in range(3)]
i=0 j[0]--->[1,4,7]
i=1 j[1]--->[2,5,8]
i=2 j[2]--->[3,6,9]
for i in range(3):--->循环3次,i=0,1,2
for j in a:---->循环3次,j=第一行,第二行,第三行
j[i]---->第一次:1,4,7
第二次:2,5,8
第三次:3,6,9
>>> a=[[1,2,3],[4,5,6],[7,8,9]] >>> [[j[i] for j in a] for i in range(3)] [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
升级练习:删除二维矩阵中的某一列。
[[i[j] for j in [1,2]] for i in a]
a=[[1,2,3],[4,5,6],[7,8,9]]
for i in a:--->循环三次:
i:第一次:[1,2,3]
i:第二次:[4,5,6]
i:第三次:[7,8,9]
[i[j] for j in [1,2]]----->[i[1],i[2]]
>>> [[i[j] for j in range(3)] for i in a]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> [[i[j] for j in [1,2]] for i in a]
[[2, 3], [5, 6], [8, 9], [11, 12]]
>>> [[i[j] for j in [0,2]] for i in a]
[[1, 3], [4, 6], [7, 9], [10, 12]]