# 如何在 Python 中获取一个列表的平均值

Syed Moiz Haider 2023年5月8日

## 使用 `statistics` 库获取列表的平均值

``````import statistics

list = [1, 2, 3, 4, 5, 6]
mean = statistics.mean(list)
print(mean)
``````

``````3.5
``````

## 使用 `sum()/len()` 查找 Python 列表的平均值

`sum(list)` 获得给定列表的总和，`len(list)` 返回列表的长度。

``````data = [1, 2, 3, 4, 5, 6]
mean = sum(data) / len(data)
print(mean)
``````

``````3.5
``````

### 使用 `numpy.mean()` 查找 Python 列表的平均值

``````import numpy

data = [1, 2, 3, 4, 5, 6]
mean = numpy.mean(data)
print(mean)
``````

``````3.5
``````

## 在 Python 2 中使用 `sum()/float(len())` 查找 Python 列表的平均数

``````data = [1, 2, 3, 4, 5, 6]
mean = sum(data) / float(len(data))
print(mean)
``````

``````3.5
``````

``````data = [1, 2, 3, 4, 5, 6]
mean = sum(data) / len(data)
print(mean)
``````

``````3
``````

Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.