已知数据列表为:30,31,47,50,52,52,56,60,63,70,70,110,编写相应函数完成下面各指标的计算。mean(均值)median(中位数)mode(众数)midrange(中列数)方差标准差
时间: 2024-09-19 19:04:39 浏览: 62
西南交通大学-数据结构第5次作业
为了计算给定数据集的均值、中位数、众数、中列数(也称为四分位距)、方差和标准差,您可以创建一个Python函数来处理这些任务。以下是对应的代码:
```python
def calculate_statistics(numbers):
mean = sum(numbers) / len(numbers)
median = sorted(numbers)[len(numbers) // 2] if len(numbers) % 2 else (sorted(numbers)[len(numbers) // 2 - 1] + sorted(numbers)[len(numbers) // 2]) / 2
mode = max(set(numbers), key=numbers.count) # 使用collections.Counter可能更高效
mid_range = numbers[len(numbers) // 2] - numbers[0]
variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)
std_dev = variance ** 0.5
return {
"Mean": mean,
"Median": median,
"Mode": mode,
"Mid-range": mid_range,
"Variance": variance,
"Standard Deviation": std_dev
}
data = [30, 31, 47, 50, 52, 52, 56, 60, 63, 70, 70, 110]
stats = calculate_statistics(data)
print(f"Numbers: {data}")
print(f"Statistics:\n{stats}\n")
阅读全文