python案例统计红黄牌数量哪队更多?

wen python案例 4

统计红黄牌数量哪队更多 - Python案例

案例背景

假设有两支球队的比赛数据,需要统计哪支球队获得的红黄牌更多。

python案例统计红黄牌数量哪队更多?

基础版本

# 模拟比赛数据
match_data = [
    {"team": "A队", "player": "张三", "card": "yellow"},
    {"team": "B队", "player": "李四", "card": "red"},
    {"team": "A队", "player": "王五", "card": "yellow"},
    {"team": "A队", "player": "赵六", "card": "red"},
    {"team": "B队", "player": "钱七", "card": "yellow"},
    {"team": "B队", "player": "孙八", "card": "yellow"},
    {"team": "A队", "player": "周九", "card": "yellow"},
]
# 统计各队红黄牌
stats = {}
for record in match_data:
    team = record["team"]
    card = record["card"]
    if team not in stats:
        stats[team] = {"yellow": 0, "red": 0}
    stats[team][card] += 1
# 输出统计结果
print("=" * 40)
print("红黄牌统计结果")
print("=" * 40)
for team, count in stats.items():
    print(f"{team}: 黄牌 {count['yellow']} 张, 红牌 {count['red']} 张, "
          f"总计 {count['yellow'] + count['red']} 张")
# 判断哪队红黄牌更多
team_a = stats.get("A队", {"yellow": 0, "red": 0})
team_b = stats.get("B队", {"yellow": 0, "red": 0})
total_a = team_a["yellow"] + team_a["red"]
total_b = team_b["yellow"] + team_b["red"]
print("\n" + "=" * 40)
if total_a > total_b:
    print(f"A队红黄牌更多({total_a} vs {total_b})")
elif total_b > total_a:
    print(f"B队红黄牌更多({total_b} vs {total_a})")
else:
    print(f"两队红黄牌数量相同({total_a})")

进阶版本(使用 pandas + 加权统计)

import pandas as pd
# 构造数据
df = pd.DataFrame({
    "team": ["A队", "B队", "A队", "A队", "B队", "B队", "A队"],
    "player": ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九"],
    "card": ["yellow", "red", "yellow", "red", "yellow", "yellow", "yellow"]
})
# 加权:红牌记2分(可选,体现红牌更严重)
df["weight"] = df["card"].map({"yellow": 1, "red": 2})
# 透视统计
summary = df.groupby(["team", "card"]).size().unstack(fill_value=0)
summary["总计"] = summary.sum(axis=1)
summary = summary.sort_values("总计", ascending=False)
print("各队红黄牌统计:")
print(summary)
print()
# 判断哪队更多
top_team = summary["总计"].idxmax()
print(f"红黄牌最多的球队是:{top_team}(共 {summary.loc[top_team, '总计']} 张)")
# 加权后对比
weight_summary = df.groupby("team")["weight"].sum()
print("\n加权积分(红牌2分,黄牌1分):")
print(weight_summary)
print(f"加权后最多的是:{weight_summary.idxmax()}")

运行结果

========================================
红黄牌统计结果
========================================
A队: 黄牌 3 张, 红牌 1 张, 总计 4 张
B队: 黄牌 2 张, 红牌 1 张, 总计 3 张
========================================
A队红黄牌更多(4 vs 3)

进阶版输出:

各队红黄牌统计:
card  red  yellow  总计
team                  
A队     1       3     4
B队     1       2     3
红黄牌最多的球队是:A队(共 4 张)
加权积分(红牌2分,黄牌1分):
team
A队    5
B队    4
加权后最多的是:A队
步骤 说明
数据准备 用 dict 或 DataFrame 保存每张牌记录
分组统计 按球队 (team) 和 牌型 (card) 计数
汇总对比 计算总数,用 > 或 idxmax() 找出最多
扩展优化 可对红牌加权、按球员统计、按联赛/轮次细化

如果你想接入真实 API 数据(如 football-data.org)、或改成可视化图表(matplotlib 柱状图),告诉我具体需求即可。

上一篇综合python案例,中卫组合默契度如何量化?

下一篇当前分类已是最新一篇

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