python随机生成两个3*4的整数矩阵,计算两个矩阵的和
时间: 2024-05-08 15:15:10 浏览: 88
可以使用random模块中的randint函数随机生成整数,再使用嵌套的列表推导式生成两个矩阵。然后使用嵌套的for循环计算两个矩阵的和,并将结果保存到一个新的矩阵中。代码如下:
```python
import random
# 随机生成两个3*4的整数矩阵
matrix1 = [[random.randint(1, 10) for j in range(4)] for i in range(3)]
matrix2 = [[random.randint(1, 10) for j in range(4)] for i in range(3)]
# 计算两个矩阵的和
result = [[0 for j in range(4)] for i in range(3)]
for i in range(3):
for j in range(4):
result[i][j] = matrix1[i][j] + matrix2[i][j]
# 打印结果
print("矩阵1:")
for row in matrix1:
print(row)
print("矩阵2:")
for row in matrix2:
print(row)
print("两个矩阵的和:")
for row in result:
print(row)
```
运行结果如下:
```
矩阵1:
[1, 9, 9, 3]
[2, 10, 8, 10]
[3, 1, 10, 8]
矩阵2:
[7, 4, 8, 7]
[1, 10, 6, 8]
[9, 9, 6, 1]
两个矩阵的和:
[8, 13, 17, 10]
[3, 20, 14, 18]
[12, 10, 16, 9]
```
阅读全文