python求总个数、平均数、方差、中位数
时间: 2024-10-11 21:09:28 浏览: 24
python求平均数、方差、中位数的例子
在Python中,计算一组数值的总个数(总数)、平均数(均值)、方差和中位数,可以使用内置函数或相应的统计模块。这里以numpy和statistics库为例:
1. 总个数(数量):
```python
numbers = [1, 2, 3, 4, 5]
total_count = len(numbers)
```
2. 平均数(均值):
```python
import numpy as np
average = np.mean(numbers)
```
或者使用statistics库:
```python
from statistics import mean
average = mean(numbers)
```
3. 方差:
```python
variance_np = np.var(numbers)
variance_stats = statistics.variance(numbers)
```
4. 中位数(如果列表长度是奇数):
```python
median_np = np.median(numbers)
median_stats = statistics.median(numbers)
```
如果列表长度是偶数,中位数取中间两个数的平均值:
```python
sorted_numbers = sorted(numbers)
if len(sorted_numbers) % 2 == 0:
median = (sorted_numbers[len(numbers) // 2 - 1] + sorted_numbers[len(numbers) // 2]) / 2
else:
median = sorted_numbers[len(numbers) // 2]
```
阅读全文