大家好,又见面了,我是你们的朋友全栈君。
* for in 嵌套列表
def transpose1(matrix):
cols = len(matrix[0])
return [[row[i] for row in matrix] for i in range(0,cols)]
def transpose2(matrix):
transposed = []
for i in range(len(matrix[0])):
transposed.append([row[i] for row in matrix])
return transposed
def transpose3(matrix):
transposed = []
for i in range(len(matrix[0])):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
return transposed
test:
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
print(transpose1(matrix))
print(transpose2(matrix))
print(transpose3(matrix))
output:
[Running] python -u “j:\python\matrix.py”
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[Done] exited with code=0 in 0.125 seconds
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/137109.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...