You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中遍历双列表统计匹配项,实现贝叶斯概率计算函数

修正基于贝叶斯定理的雨天概率计算函数

需求说明

计算未举办比赛时当天为雨天的概率,即条件概率 P(Rainy | No)。核心逻辑是统计weather_data与play_data同索引下,天气为指定值(如'Rainy')且比赛状态为指定值(如'No')的次数,再除以比赛状态为指定值的总次数。

给定数据集

weather_data = ['Sunny','Overcast','Rainy','Sunny','Sunny','Overcast','Rainy','Rainy','Sunny',
                'Rainy','Sunny','Overcast','Overcast','Rainy']
play_data = ['No','Yes','Yes','Yes','Yes','Yes','No','No','Yes','Yes','No','Yes','Yes','No']

原函数的问题

原函数存在多处逻辑错误:

  • 循环遍历的是weather_data的元素而非索引,用字符串作为列表索引会直接报错
  • 条件判断仅写了表达式,未用if语句包裹,无法触发计数逻辑
  • yes+1是无效表达式,未对yes进行赋值操作,导致yes始终为0
  • 硬编码了"Rainy"和"No",未使用函数传入的weather和played参数,丧失通用性

修正后的函数

def likelihood(weather, played, weather_data, play_data):
    # 统计满足条件的次数
    match_count = 0
    # 遍历索引,确保两个列表同位置对应
    for idx in range(len(weather_data)):
        if weather_data[idx] == weather and play_data[idx] == played:
            match_count += 1
    # 统计指定比赛状态的总次数
    total_played = play_data.count(played)
    # 处理除零情况,避免报错
    return float(match_count / total_played) if total_played != 0 else 0.0

验证示例

调用函数计算未比赛时雨天的概率:

# 计算P(Rainy | No)
result = likelihood('Rainy', 'No', weather_data, play_data)
print(result)  # 输出应为 3/5 = 0.6

内容的提问来源于stack exchange,提问作者Zuzanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:10:38