产生一个nxn的整型二维数组并完成如下功能。 (1)找出最大值和最小值 (2)统计平均值 (3)分别求出主、副对角线的元素的平均值 (4)求出数组外圈元素之和 (5)把主对角线以下的元素设置为0
时间: 2023-05-25 19:03:20 浏览: 136
数组{1,3,5,-2,4,6},要求获取:最大值、最小值、元素和、平均
```python
import random
# 生成一个nxn的二维数组
n = 5
arr = [[random.randint(1, 100) for j in range(n)] for i in range(n)]
# 找出最大值和最小值
max_val = max(max(row) for row in arr)
min_val = min(min(row) for row in arr)
print("最大值:", max_val)
print("最小值:", min_val)
# 统计平均值
sum_val = sum(sum(row) for row in arr)
average = sum_val / (n * n)
print("平均值:", average)
# 分别求出主、副对角线的元素的平均值
sum_main = sum(arr[i][i] for i in range(n))
sum_vic = sum(arr[i][n-i-1] for i in range(n))
average_main = sum_main / n
average_vic = sum_vic / n
print("主对角线平均值:", average_main)
print("副对角线平均值:", average_vic)
# 求出数组外圈元素之和
outer_sum = sum(arr[0]) + sum(arr[-1]) + sum(arr[i][0] + arr[i][-1] for i in range(1, n-1))
print("外圈元素之和:", outer_sum)
# 把主对角线以下的元素设置为0
for i in range(n):
for j in range(n):
if j < i:
arr[i][j] = 0
print("主对角线以下的元素设置为0后:")
for row in arr:
print(row)
```
阅读全文