Python循环统计案例如何计算数据

wen python案例 23

本文目录导读:

Python循环统计案例如何计算数据

  1. 基本统计量计算
  2. 频次统计
  3. 分组统计
  4. 累积统计
  5. 条件统计
  6. 嵌套循环统计数据
  7. 实时数据统计

我来介绍几种Python循环统计数据的经典案例和方法。

基本统计量计算

示例:计算平均值、最大值、最小值

# 数据准备
scores = [85, 92, 78, 95, 88, 76, 90, 82, 87, 93]
# 使用循环计算统计量
total = 0
max_score = scores[0]
min_score = scores[0]
count = 0
for score in scores:
    total += score
    count += 1
    if score > max_score:
        max_score = score
    if score < min_score:
        min_score = score
average = total / count
print(f"总分: {total}")
print(f"平均分: {average:.2f}")
print(f"最高分: {max_score}")
print(f"最低分: {min_score}")
print(f"人数: {count}")

频次统计

示例:统计单词出现次数

# 文本数据
text = "python java python c++ java python javascript python java c++"
# 拆分单词
words = text.split()
# 使用循环统计频次
word_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
# 输出结果
print("单词频次统计:")
for word, count in word_count.items():
    print(f"'{word}': {count}次")

分组统计

示例:按区间统计成绩分布

# 成绩数据
scores = [85, 92, 78, 95, 88, 76, 90, 82, 87, 93, 45, 67, 55]
# 定义区间
intervals = {
    "优秀(90-100)": 0,
    "良好(80-89)": 0,
    "中等(70-79)": 0,
    "及格(60-69)": 0,
    "不及格(<60)": 0
}
# 统计各区间人数
for score in scores:
    if score >= 90:
        intervals["优秀(90-100)"] += 1
    elif score >= 80:
        intervals["良好(80-89)"] += 1
    elif score >= 70:
        intervals["中等(70-79)"] += 1
    elif score >= 60:
        intervals["及格(60-69)"] += 1
    else:
        intervals["不及格(<60)"] += 1
print("成绩分布统计:")
for interval, count in intervals.items():
    print(f"{interval}: {count}人")

累积统计

示例:计算累积和与累积平均值

# 每日销售数据
daily_sales = [120, 85, 200, 150, 175, 90, 160]
# 计算累积统计
cumulative_sum = 0
cumulative_avg = []
print("每日累积统计:")
for i, sale in enumerate(daily_sales, 1):
    cumulative_sum += sale
    avg = cumulative_sum / i
    cumulative_avg.append(avg)
    print(f"第{i}天: 当日{sale}元, 累积销售额{cumulative_sum}元, 累积平均{avg:.1f}元")

条件统计

示例:统计满足条件的数据

# 学生成绩数据
students = [
    {"name": "张三", "score": 85, "age": 18},
    {"name": "李四", "score": 92, "age": 19},
    {"name": "王五", "score": 78, "age": 17},
    {"name": "赵六", "score": 95, "age": 20},
    {"name": "孙七", "score": 88, "age": 18}
]
# 统计条件:成绩>=85且年龄>=18的学生
filtered_students = []
filter_count = 0
filter_total_score = 0
for student in students:
    if student["score"] >= 85 and student["age"] >= 18:
        filtered_students.append(student)
        filter_count += 1
        filter_total_score += student["score"]
# 输出结果
print(f"符合条件的优秀学生({filter_count}人):")
for student in filtered_students:
    print(f"  {student['name']}: {student['score']}分, {student['age']}岁")
if filter_count > 0:
    print(f"平均分: {filter_total_score/filter_count:.1f}")

嵌套循环统计数据

示例:二维数据统计

# 多个班级的成绩数据
class_scores = [
    [85, 90, 78, 92],  # 班级1
    [75, 88, 95, 82],  # 班级2
    [90, 85, 88, 86],  # 班级3
    [72, 78, 85, 90]   # 班级4
]
print("各班级统计:")
total_all = 0
count_all = 0
class_averages = []
for class_idx, class_s in enumerate(class_scores, 1):
    class_total = 0
    for score in class_s:
        class_total += score
    class_avg = class_total / len(class_s)
    class_averages.append(class_avg)
    total_all += class_total
    count_all += len(class_s)
    print(f"班级{class_idx}: 总分={class_total}, 平均分={class_avg:.1f}")
print(f"\n全校统计:")
print(f"总人数: {count_all}")
print(f"总分: {total_all}")
print(f"平均分: {total_all/count_all:.1f}")
# 找出最好的班级
best_class = class_averages.index(max(class_averages)) + 1
print(f"最佳班级: 班级{best_class} (平均分: {max(class_averages):.1f})")

实时数据统计

示例:流式数据处理

import random
# 模拟实时数据流
def generate_data_stream():
    """生成模拟数据流"""
    base_values = [10, 15, 12, 18, 14, 16, 11, 13]
    return base_values + [random.randint(5, 25) for _ in range(5)]
# 实时统计
def real_time_statistics(data_stream):
    window_size = 3  # 滑动窗口大小
    stats = {
        "window_averages": [],
        "running_total": 0,
        "running_count": 0,
        "max_value": float('-inf'),
        "min_value": float('inf')
    }
    window = []
    for i, value in enumerate(data_stream, 1):
        # 更新运行统计
        stats["running_total"] += value
        stats["running_count"] += 1
        stats["max_value"] = max(stats["max_value"], value)
        stats["min_value"] = min(stats["min_value"], value)
        # 滑动窗口统计
        window.append(value)
        if len(window) > window_size:
            window.pop(0)
        window_avg = sum(window) / len(window)
        stats["window_averages"].append(window_avg)
        print(f"数据{i}: 值={value}, "
              f"运行平均={stats['running_total']/stats['running_count']:.2f}, "
              f"窗口平均={window_avg:.2f}")
    return stats
# 运行实时统计
print("实时数据流统计:")
data = generate_data_stream()
result = real_time_statistics(data)
print(f"\n最终统计:")
print(f"最大值: {result['max_value']}")
print(f"最小值: {result['min_value']}")
print(f"最终平均: {result['running_total']/result['running_count']:.2f}")

使用enumerate获取索引

for i, value in enumerate(data):
    print(f"第{i+1}个数据: {value}")

使用zip并行迭代

names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}分")

统计性能优化

# 使用局部变量提高循环效率
total = 0
local_scores = scores  # 局部引用
for score in local_scores:
    total += score

这些案例覆盖了Python循环统计的常见场景,可以根据实际需求进行调整和组合使用,记住选择合适的数据结构和算法可以大大提高统计效率。

抱歉,评论功能暂时关闭!