创建一个3乘3矩阵,其元素为分别为1、...、9,如下图所示。 [1 2 3] [4 5 6] [7 8 9] ① 求每行、每列和数组的最大值和最小值 ② 求每行、每列和数组的峰值 ③ 求每行、每列和数组的和,对角线和 ④ 求每行、每列和数组的平均值和方差
时间: 2024-09-17 07:02:08 浏览: 42
创建一个3x3矩阵,并按照要求进行操作:
```python
# 定义3x3矩阵
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 操作步骤
# ① 求每行、每列和数组的最大值和最小值
row_max = [max(row) for row in matrix]
row_min = [min(row) for row in matrix]
col_max = [max(col) for col in zip(*matrix)] # *matrix用于展平列
col_min = [min(col) for col in zip(*matrix)]
array_max = max(max(matrix), max(row_max), max(col_max))
array_min = min(min(matrix), min(row_min), min(col_min))
# ② 求每行、每列和数组的峰值(即最大值)
row_peaks = [max(row) for row in matrix]
col_peaks = row_peaks
# 对于数组,如果矩阵中有相同的最大值,则需遍历确认
if array_max == max(row_max):
array_peak_index = matrix.index(max(matrix)) # 获取最大值所在位置
else:
array_peaks = []
# ③ 求每行、每列和数组的和,以及对角线和
row_sums = [sum(row) for row in matrix]
col_sums = sum(zip(*matrix), []) # 同理展平并求和
diag_sum = sum(matrix[i][i] for i in range(3))
# ④ 求每行、每列和数组的平均值和方差
row_avgs = [sum(row) / len(row) for row in matrix]
col_avgs = sum(col_sums) / len(col_sums)
array_avg = sum(array_sum) / len(matrix)
row_vars = [sum((num - avg)**2 for num in row) for avg, row in zip(row_avgs, matrix)]
col_vars = sum((num - col_avg)**2 for num in col_avgs)
array_var = sum((num - array_avg)**2 for num in array_sum) / len(matrix)
# 结果展示
print("矩阵:\n", matrix)
print("\n每行最大值:", row_max)
print("每行最小值:", row_min)
print("每列最大值:", col_max)
print("每列最小值:", col_min)
print("数组最大值:", array_max, "峰值得到吗?: ", array_peaks)
print("每行和:", row_sums)
print("每列和:", col_sums)
print("对角线和:", diag_sum)
print("每行平均值:", row_avgs)
print("每列平均值:", col_avgs)
print("数组平均值:", array_avg)
print("每行方差:", row_vars)
print("每列方差:", col_vars)
print("数组方差:", array_var)
```
阅读全文