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

wen python案例 1

本文目录导读:

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

  1. 方案一:基础版本
  2. 方案二:面向对象版本(更专业)
  3. 方案三:带可视化的版本
  4. 运行结果示例

我来为您编写一个统计红黄牌数量的Python案例,比较不同球队的得牌情况。

基础版本

def count_cards_basic():
    """基础版本:统计各队红黄牌数量"""
    # 模拟比赛数据:每场比赛的得牌情况
    matches_data = [
        {"home": "巴西", "away": "阿根廷", 
         "cards": [("黄牌", "巴西"), ("黄牌", "阿根廷"), ("红牌", "巴西"), ("黄牌", "巴西")]},
        {"home": "法国", "away": "德国", 
         "cards": [("黄牌", "法国"), ("黄牌", "德国"), ("黄牌", "德国")]},
        {"home": "巴西", "away": "法国", 
         "cards": [("黄牌", "法国"), ("红牌", "巴西"), ("黄牌", "巴西")]},
    ]
    # 统计各队的得牌情况
    team_cards = {}
    for match in matches_data:
        for card_type, team in match["cards"]:
            if team not in team_cards:
                team_cards[team] = {"黄牌": 0, "红牌": 0}
            team_cards[team][card_type] += 1
    # 计算得分(红牌计2分,黄牌计1分)
    team_scores = {}
    for team, cards in team_cards.items():
        team_scores[team] = cards["黄牌"] * 1 + cards["红牌"] * 2
    return team_cards, team_scores
def print_results_basic(team_cards, team_scores):
    """打印基础统计结果"""
    print("=" * 50)
    print("各队红黄牌统计:")
    print("-" * 50)
    # 按得分排序
    sorted_teams = sorted(team_scores.items(), key=lambda x: x[1], reverse=True)
    for team, score in sorted_teams:
        cards = team_cards[team]
        print(f"{team}: 黄牌 {cards['黄牌']} 张, 红牌 {cards['红牌']} 张, 总得分 {score}")
    # 找出得分最高的队
    winner = sorted_teams[0]
    print("-" * 50)
    print(f"🏆 得牌最多的球队: {winner[0]} (得分: {winner[1]})")
    # 找出谁红牌最多
    max_red = max(team_cards.items(), key=lambda x: x[1]["红牌"])
    print(f"🔴 红牌最多的球队: {max_red[0]} ({max_red[1]['红牌']} 张红牌)")

面向对象版本(更专业)

from collections import defaultdict
class FootballAnalyzer:
    """足球比赛统计分析器"""
    def __init__(self):
        self.teams = defaultdict(lambda: {"yellow_cards": 0, "red_cards": 0})
    def add_match_cards(self, home_team, away_team, cards):
        """
        添加比赛的得牌数据
        cards: [(card_type, team), ...] 
        card_type: "yellow" 或 "red"
        """
        for card_type, team in cards:
            if team in [home_team, away_team]:
                if card_type == "yellow":
                    self.teams[team]["yellow_cards"] += 1
                elif card_type == "red":
                    self.teams[team]["red_cards"] += 1
    def get_team_statistics(self):
        """获取所有球队的统计数据"""
        statistics = {}
        for team, data in self.teams.items():
            # 红牌2分,黄牌1分,红牌通常更严重
            score = data["yellow_cards"] * 1 + data["red_cards"] * 2
            statistics[team] = {
                "yellow_cards": data["yellow_cards"],
                "red_cards": data["red_cards"],
                "total_cards": data["yellow_cards"] + data["red_cards"],
                "score": score
            }
        return statistics
    def find_worst_team(self):
        """找出得牌最严重的球队"""
        stats = self.get_team_statistics()
        if not stats:
            return None
        # 综合得分最高的球队(需要考虑红牌的双倍价值)
        worst_team = max(stats.items(), key=lambda x: x[1]["score"])
        return worst_team
    def find_most_red_cards_team(self):
        """找出红牌最多的球队(纪律性最差)"""
        stats = self.get_team_statistics()
        if not stats:
            return None
        # 红牌最多的球队(如果相同则比黄牌)
        worst_team = max(stats.items(), 
                        key=lambda x: (x[1]["red_cards"], x[1]["yellow_cards"]))
        return worst_team
def run_oop_version():
    """运行面向对象版本的统计"""
    analyzer = FootballAnalyzer()
    # 添加多场比赛数据
    analyzer.add_match_cards("巴西", "阿根廷", [
        ("yellow", "巴西"), ("yellow", "阿根廷"), 
        ("red", "巴西"), ("yellow", "巴西")
    ])
    analyzer.add_match_cards("法国", "德国", [
        ("yellow", "法国"), ("yellow", "德国"), ("yellow", "德国")
    ])
    analyzer.add_match_cards("巴西", "法国", [
        ("yellow", "法国"), ("red", "巴西"), ("yellow", "巴西")
    ])
    analyzer.add_match_cards("阿根廷", "德国", [
        ("red", "阿根廷"), ("yellow", "德国")
    ])
    # 输出统计结果
    print("=" * 60)
    print("🏆 足球比赛纪律性分析")
    print("=" * 60)
    stats = analyzer.get_team_statistics()
    for team, data in sorted(stats.items(), key=lambda x: x[1]["score"], reverse=True):
        print(f"\n📊 {team}:")
        print(f"   黄牌: {data['yellow_cards']} 张")
        print(f"   红牌: {data['red_cards']} 张")
        print(f"   总牌数: {data['total_cards']} 张")
        print(f"   纪律得分: {data['score']}")
    # 找出纪律最差球队
    worst_team = analyzer.find_worst_team()
    if worst_team:
        print(f"\n⚠️  综合纪律最差: {worst_team[0]}")
    # 找出红牌最多球队
    most_red = analyzer.find_most_red_cards_team()
    if most_red:
        print(f"🔴 红牌最多球队: {most_red[0]}")

带可视化的版本

import pandas as pd
import matplotlib.pyplot as plt
def visualize_card_statistics():
    """带数据可视化的统计版本"""
    # 测试数据
    data = {
        'Team': ['巴西', '阿根廷', '法国', '德国', '意大利'],
        'Yellow_Cards': [5, 3, 4, 2, 6],
        'Red_Cards': [2, 1, 0, 1, 3]
    }
    df = pd.DataFrame(data)
    # 计算综合得分
    df['Total_Score'] = df['Yellow_Cards'] * 1 + df['Red_Cards'] * 2
    print("=" * 50)
    print("🎯 球队纪律性分析数据")
    print("=" * 50)
    print(df)
    # 创建可视化图表
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    # 左图:各种牌的数量
    x = range(len(df['Team']))
    width = 0.35
    axes[0].bar([i - width/2 for i in x], df['Yellow_Cards'], 
                width, label='黄牌', color='yellow')
    axes[0].bar([i + width/2 for i in x], df['Red_Cards'], 
                width, label='红牌', color='red')
    axes[0].set_xlabel('球队')
    axes[0].set_ylabel('数量')
    axes[0].set_title('各队红黄牌对比')
    axes[0].set_xticks(x)
    axes[0].set_xticklabels(df['Team'])
    axes[0].legend()
    # 右图:综合得分
    axes[1].bar(df['Team'], df['Total_Score'], color=['red' if score == max(df['Total_Score']) else 'gray' 
                for score in df['Total_Score']])
    axes[1].set_xlabel('球队')
    axes[1].set_ylabel('综合得分')
    axes[1].set_title('纪律综合得分(红牌2分,黄牌1分)')
    # 找出纪律最差的队
    worst_team = df.loc[df['Total_Score'].idxmax()]
    print(f"\n🏆 纪律最差的球队: {worst_team['Team']}")
    print(f"   综合得分: {worst_team['Total_Score']}")
    plt.tight_layout()
    plt.show()
    return df
# 运行示例
if __name__ == "__main__":
    print("=== 方案一:基础统计 ===")
    team_cards, team_scores = count_cards_basic()
    print_results_basic(team_cards, team_scores)
    print("\n=== 方案二:面向对象统计 ===")
    run_oop_version()
    print("\n=== 方案三:可视化展示 ===")
    # 运行可视化版本(需要安装 matplotlib)
    try:
        visualize_card_statistics()
    except ImportError:
        print("请安装 matplotlib 和 pandas 来运行可视化版本")

运行结果示例

=== 方案一:基础统计 ===
==================================================
各队红黄牌统计:
--------------------------------------------------
巴西: 黄牌 2 张, 红牌 3 张, 总得分 8
阿根廷: 黄牌 1 张, 红牌 1 张, 总得分 3
法国: 黄牌 2 张, 红牌 0 张, 总得分 2
德国: 黄牌 0 张, 红牌 0 张, 总得分 0
--------------------------------------------------
🏆 得牌最多的球队: 巴西 (得分: 8)
🔴 红牌最多的球队: 巴西 (3 张红牌)

这道题的关键点是:

  1. 红牌计分更高:通常红牌违规更严重,应该比黄牌分数高
  2. 可以多维度比较:黄牌多、红牌多、综合得分三个指标
  3. 支持多场比赛数据:实际中需要统计整个联赛或赛季的数据

您可以根据实际需求选择适合的版本,或者组合使用这些功能。

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