统计红黄牌数量哪队更多的Python案例
下面通过几个不同场景的案例,演示如何统计红黄牌数量并比较哪队更多。

基础版(手动输入数据)
def count_cards(cards):
"""
统计红黄牌数量
cards: 列表,每个元素为 (队伍, 牌类型) 的元组
"""
stats = {}
for team, card in cards:
if team not in stats:
stats[team] = {'黄牌': 0, '红牌': 0}
stats[team][card] += 1
return stats
# 模拟比赛数据:(队伍, 牌类型)
match_cards = [
('A队', '黄牌'), ('A队', '黄牌'), ('A队', '红牌'),
('B队', '黄牌'), ('B队', '黄牌'), ('B队', '黄牌'),
('A队', '黄牌'),
]
stats = count_cards(match_cards)
print("各队红黄牌统计:")
for team, data in stats.items():
print(f" {team}: 黄牌 {data['黄牌']} 张, 红牌 {data['红牌']} 张, "
f"总计 {data['黄牌'] + data['红牌']} 张")
# 比较哪队牌更多
total = {team: data['黄牌'] + data['红牌'] for team, data in stats.items()}
more_team = max(total, key=total.get)
print(f"\n>>> {more_team} 的牌更多(共 {total[more_team]} 张)")
输出:
各队红黄牌统计:
A队: 黄牌 3 张, 红牌 1 张, 总计 4 张
B队: 黄牌 3 张, 红牌 0 张, 总计 3 张
>>> A队 的牌更多(共 4 张)
从字典/DataFrame读取数据
import pandas as pd
# 模拟数据
data = {
'队伍': ['A队', 'A队', 'A队', 'B队', 'B队', 'B队', 'B队', 'A队'],
'牌类型': ['黄牌', '黄牌', '红牌', '黄牌', '黄牌', '黄牌', '红牌', '黄牌']
}
df = pd.DataFrame(data)
# 透视统计
pivot = df.groupby(['队伍', '牌类型']).size().unstack(fill_value=0)
pivot['合计'] = pivot.sum(axis=1)
print("各队红黄牌统计表:")
print(pivot)
# 判断哪队更多
max_team = pivot['合计'].idxmax()
print(f"\n>>> 牌数最多的队伍是:{max_team}(共 {pivot.loc[max_team, '合计']} 张)")
输出:
各队红黄牌统计表:
牌类型 红牌 黄牌 合计
队伍
A队 1 3 4
B队 1 3 4
>>> 牌数最多的队伍是:A队(共 4 张)
带权重的比较(红牌权重更高)
有时红牌比黄牌更"严重",可以用加权方式比较:
def compare_cards_weighted(cards, red_weight=2):
"""
红牌权重默认为2(1张红=2张黄)
"""
scores = {}
for team, card in cards:
if team not in scores:
scores[team] = {'黄牌': 0, '红牌': 0, '加权分': 0}
scores[team][card] += 1
scores[team]['加权分'] += 1 if card == '黄牌' else red_weight
print("加权统计(红牌权重=2):")
for team, s in scores.items():
print(f" {team}: 黄{s['黄牌']}张 红{s['红牌']}张 → 加权分 {s['加权分']}")
winner = max(scores, key=lambda t: scores[t]['加权分'])
print(f"\n>>> 综合来看,{winner} 的牌更严重")
return scores
match_cards = [
('A队', '黄牌'), ('A队', '黄牌'), ('A队', '红牌'),
('B队', '黄牌'), ('B队', '黄牌'), ('B队', '黄牌'),
]
compare_cards_weighted(match_cards)
输出:
加权统计(红牌权重=2):
A队: 黄2张 红1张 → 加权分 4
B队: 黄3张 红0张 → 加权分 3
>>> 综合来看,A队 的牌更严重
| 场景 | 方法 |
|---|---|
| 简单统计 | dict 累计计数 |
| 表格分析 | pandas groupby + unstack |
| 数据来源 | 列表元组 / CSV / DataFrame |
| 比较逻辑 | max(dict, key=dict.get) 或 idxmax() |
| 进阶 | 加权比较、平局处理、可视化 |
如果需要接入真实比赛数据(API/CSV)或加上柱状图可视化(matplotlib),可以告诉我,我继续补充完整代码 👍
版权声明:本站文章为原创整理,转载请注明出处。