python嵌套列表展示

Python的列表还可以嵌套,以下用三种方法来说明
1 方法一
  1. >>> matrix =[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
  2. >>> transposed =[]
  3. >>>for i in range(4):
  4. transposed_row =[]
  5. for row in matrix:
  6. transposed_row.append(row[i])
  7. transposed.append(transposed_row)
  8. >>> transposed
  9. [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
2 方法二
  1. >>> transposed =[]
  2. >>>for i in range(4):
  3. transposed.append([row[i]for row in matrix])
  4. >>> transposed
  5. [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
3 方法三
  1. >>>[[row[i]for row in matrix]for i in range(4)]
  2. [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]

你可能感兴趣的:(python)