Python – 获取矩阵均值
给定一个矩阵,求其均值。
Input : test_list = [[5, 6, 7], [7, 5, 6]]
Output : 6.0
Explanation : 36 / 6 = 6.0
Input : test_list = [[5, 6, 7, 4, 8]]
Output : 6.0
Explanation : 30 / 5 = 6.0
方法 #1:使用列表推导 + sum() + len() + zip()
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 和 len() 执行均值计算,zip() 以及 *运算符执行提取矩阵行的每个元素的任务。
Python3
# Python3 code to demonstrate working of
# Matrix Mean
# Using list comprehension + sum() + len() + zip()
# initializing lists
test_list = [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]]
# printing original list
print("The original list : " + str(test_list))
# zip() to get all elements
# sum() / len() gives mean
# extracts column mean
res = [sum(idx) / len(idx) for idx in zip(*test_list)]
# extracts all elements mean
res = sum(res) / len(res)
# printing result
print("Matrix Mean : " + str(res))
Python3
# Python3 code to demonstrate working of
# Matrix Mean
# Using mean() + zip() + list comprehension
from statistics import mean
# initializing lists
test_list = [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]]
# printing original list
print("The original list : " + str(test_list))
# zip() to get all elements
# mean() gives mean
# extracts column mean
res = [mean(idx) for idx in zip(*test_list)]
# extracts all elements mean
res = mean(res)
# printing result
print("Matrix Mean : " + str(res))
输出
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]]
Matrix Mean : 5.25
方法 #2:使用 mean() + zip() + 列表理解
这是可以执行此任务的另一种方法。在此,我们使用 mean() 的内置方法提取均值。
Python3
# Python3 code to demonstrate working of
# Matrix Mean
# Using mean() + zip() + list comprehension
from statistics import mean
# initializing lists
test_list = [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]]
# printing original list
print("The original list : " + str(test_list))
# zip() to get all elements
# mean() gives mean
# extracts column mean
res = [mean(idx) for idx in zip(*test_list)]
# extracts all elements mean
res = mean(res)
# printing result
print("Matrix Mean : " + str(res))
输出
The original list : [[5, 6, 3], [8, 3, 1], [9, 10, 4], [8, 4, 2]]
Matrix Mean : 5.25