Python P25讲课后习题 转置矩阵
matrix = [,,
]
Tmatrix = [ for row in matrix] for i in range(4)]
#此处列表推导式没有想明白,特别是执行顺序希望有大大们解释一下
#减少括号后能理解Tmatrix = for row in matrix for i in range(4)],即为展开原矩阵
print(Tmatrix) 本帖最后由 liuzhengyuan 于 2022-8-9 23:36 编辑
Tmatrix = [ for row in matrix] for i in range(4)]
相当于:(纯手写的,不知道会不会出错)
Tmatrix = []
for row in matrix:
for i in range(4):
Tmatrix.append(row)
看来一下其他人的回复,果然,写错了(大意了){:10_250:}
应该是这样:
matrix = [,
,
]
Tmatrix = []
for row in matrix:
temp = []
for i in range(4):
temp.append(row)
Tmatrix.append(temp)
print(Tmatrix)
本帖最后由 ba21 于 2022-8-9 22:19 编辑
#分解 [ for row in matrix] for i in range(4)]
tmp = []
for i in range(4):
tmp.append( for row in matrix])
#分解 for row in matrix]
tmp = []
for i in range(4):
####
tmp2 = []
for row in matrix:
tmp2.append(row)
####
tmp.append(tmp2)
print(tmp)
# 列表推导式其实就是这样的简写 如:
v =
# 列表推导式
lst =
# 一般写法
lst = []
for i in v:
lst.append(i)
本帖最后由 一点点儿 于 2022-8-9 23:06 编辑
Tmatrix = [ for row in matrix] for i in range(4)]
相当于
Tmatrix = [ for row in matrix],
for row in matrix],
for row in matrix],
for row in matrix]]
也就是
Tmatrix = [,
,
,
]
Tmatrix = [ for row in matrix] for i in range(4)]
for循环角度理解的话相当于
Tmatrix = []
for i in range(4):
Tmatrix.append( for row in matrix]) 笔记:加括号后,列表推导式的执行顺序为:先括号外,再括号内。
页:
[1]