📜  Python - 元素的平均偏差

📅  最后修改于: 2022-05-13 01:54:44.349000             🧑  作者: Mango

Python - 元素的平均偏差

给定一个列表,任务是编写一个Python程序来计算每个列表与其列表平均值的偏差。

例子:

方法 #1:使用循环 + mean() + abs()

在这里,我们执行每个元素的迭代并使用 abs() 计算与均值的偏差,均值的计算是使用 mean() 完成的。

Python3
# Python3 code to demonstrate working of
# Mean deviation of Elements
# Using loop + mean() + abs()
from statistics import mean
  
# initializing list
test_list = [7, 5, 1, 2, 10, 3]
  
# printing original lists
print("The original list is : " + str(test_list))
  
res = []
  
# getting mean
mean_val = mean(test_list)
  
for ele in test_list:
  
    # getting deviation
    res.append(abs(ele - mean_val))
  
# printing result
print("Mean deviations : " + str(res))


Python3
# Python3 code to demonstrate working of
# Mean deviation of Elements
# Using list comprehension + mean()
from statistics import mean
  
# initializing list
test_list = [7, 5, 1, 2, 10, 3]
  
# printing original lists
print("The original list is : " + str(test_list))
  
res = []
  
# getting mean
mean_val = mean(test_list)
  
# list comprehension used for 1 liner
res = [abs(ele - mean_val) for ele in test_list]
  
# printing result
print("Mean deviations : " + str(res))


输出:

方法 #2:使用列表理解 + mean()

在这个类似的功能中使用了上述函数,不同之处在于列表理解被用作单线来解决这个问题。

蟒蛇3

# Python3 code to demonstrate working of
# Mean deviation of Elements
# Using list comprehension + mean()
from statistics import mean
  
# initializing list
test_list = [7, 5, 1, 2, 10, 3]
  
# printing original lists
print("The original list is : " + str(test_list))
  
res = []
  
# getting mean
mean_val = mean(test_list)
  
# list comprehension used for 1 liner
res = [abs(ele - mean_val) for ele in test_list]
  
# printing result
print("Mean deviations : " + str(res))

输出: