python随机生成两个3*4的整数矩阵,计算两个矩阵的和,最终分别输出三个矩阵。
时间: 2023-10-06 18:04:45 浏览: 117
在键盘上输入一个3行3列矩阵的各个元素的值(值为整数),然后输出矩阵第一行与第三行元素之和,并在fun()函数中输出
5星 · 资源好评率100%
以下是Python代码实现:
```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)]
# 计算两个矩阵的和
matrix_sum = [[matrix1[i][j] + matrix2[i][j] for j in range(4)] for i in range(3)]
# 分别输出三个矩阵
print("矩阵1:")
for i in range(3):
print(matrix1[i])
print("矩阵2:")
for i in range(3):
print(matrix2[i])
print("矩阵1和矩阵2的和:")
for i in range(3):
print(matrix_sum[i])
```
运行结果示例:
```
矩阵1:
[8, 4, 3, 2]
[10, 7, 10, 4]
[1, 9, 9, 2]
矩阵2:
[10, 6, 8, 1]
[7, 9, 5, 8]
[5, 10, 1, 7]
矩阵1和矩阵2的和:
[18, 10, 11, 3]
[17, 16, 15, 12]
[6, 19, 10, 9]
```
阅读全文