python行列互换代码
时间: 2023-10-13 21:26:37 浏览: 174
可以使用以下代码实现矩阵的行列互换:
```python
# 定义一个3x3的矩阵
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# 打印原始矩阵
print("原始矩阵:")
for row in matrix:
print(row)
# 行列互换
transpose = []
for i in range(len(matrix[0])):
new_row = []
for j in range(len(matrix)):
new_row.append(matrix[j][i])
transpose.append(new_row)
# 打印转置后的矩阵
print("转置后的矩阵:")
for row in transpose:
print(row)
```
输出结果:
```
原始矩阵:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
转置后的矩阵:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
```
相关问题
python矩阵行列互换的代码
以下是Python矩阵行列互换的代码示例:
```python
# 定义一个3x3的矩阵
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 打印原始矩阵
print("原始矩阵:")
for row in matrix:
print(row)
# 创建一个新矩阵,交换行列
new_matrix = []
for i in range(len(matrix[0])):
new_row = []
for row in matrix:
new_row.append(row[i])
new_matrix.append(new_row)
# 打印交换后的矩阵
print("交换后的矩阵:")
for row in new_matrix:
print(row)
```
输出结果:
```
原始矩阵:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
交换后的矩阵:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
```
python矩阵行列互换
你可以使用NumPy库中的transpose函数来进行矩阵的行列互换。以下是一个示例代码:
```python
import numpy as np
# 定义一个3x2的矩阵
matrix = np.array([[1, 2], [3, 4], [5, 6]])
# 输出原始矩阵
print("原始矩阵:")
print(matrix)
# 使用transpose函数进行行列互换
transposed_matrix = np.transpose(matrix)
# 输出行列互换后的矩阵
print("行列互换后的矩阵:")
print(transposed_matrix)
```
输出结果为:
```
原始矩阵:
[[1 2]
[3 4]
[5 6]]
行列互换后的矩阵:
[[1 3 5]
[2 4 6]]
```
阅读全文