# 在 Python 中计算方差

Lakshay Kapoor 2023年1月30日

## 在 Python 中使用统计模块的 `variance()` 函数计算方差

`variance()` 函数是 Python 统计模块的函数之一。该模块用于提供对数值数据执行统计操作（如均值、中位数、标准差等）的函数。

``````import statistics

list = [12, 14, 10, 6, 23, 31]
print("List : " + str(list))

var = statistics.variance(list)
print("Variance of the given list: " + str(var))
``````

``````List : [12, 14, 10, 6, 23, 31]
Variance of the given list: 86
``````

## 在 Python 中使用 NumPy 库的 `var()` 函数计算方差

NumPy 库的 `var()` 函数还可以计算给定数组列表中元素的方差。

``````import numpy as np

arr = [12, 43, 24, 17, 32]

print("Array : ", arr)
print("Variance of array : ", np.var(arr))
``````

``````Array :  [12, 43, 24, 17, 32]
Variance of array :  121.04
``````

## 在 Python 中使用 `sum()` 函数和列表推导计算方差

`sum()` 函数总结了一个可迭代对象的所有元素，如列表、元组等。

`sum()` 函数和列表推导可以帮助计算列表的方差。

``````list = [12, 43, 24, 17, 32]
average = sum(list) / len(list)
var = sum((x - average) ** 2 for x in list) / len(list)
print(var)
``````

``````121.04
``````

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.