python案例统计挑球过人次数多不多?

wen python案例 2

本文目录导读:

python案例统计挑球过人次数多不多?

  1. 场景设定
  2. 完整代码示例
  3. 使用方法
  4. 输出示例

我来给你写一个统计挑球过人次数并判断是否频繁的Python案例。

场景设定

假设我们有一个足球运动员的比赛数据,记录每次比赛中尝试挑球过人的次数。

完整代码示例

import random
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
class PlayerData:
    """足球运动员比赛数据"""
    def __init__(self, player_name):
        self.player_name = player_name
        self.match_data = []  # 存储多场比赛数据
        self.threshold = 5  # 默认阈值:单场挑球过人次数大于5次算频繁
    def generate_sample_data(self, num_matches=10):
        """生成模拟的比赛数据"""
        for i in range(num_matches):
            match = {
                'match_id': i + 1,
                'date': datetime.now() - timedelta(days=num_matches - i),
                'opponent': f'对手{i+1}队',
                'chips_attempts': random.randint(0, 15),  # 挑球过人次数
                'chips_success': random.randint(0, 10),   # 成功次数
                'total_dribbles': random.randint(5, 20),   # 总过人次数
                'playing_time': random.randint(60, 90)     # 出场时间(分钟)
            }
            match['chips_success'] = min(match['chips_success'], match['chips_attempts'])
            self.match_data.append(match)
    def add_match_data(self, date, opponent, chips_attempts, chips_success, total_dribbles, playing_time):
        """手动添加一场比赛数据"""
        match = {
            'match_id': len(self.match_data) + 1,
            'date': date,
            'opponent': opponent,
            'chips_attempts': chips_attempts,
            'chips_success': chips_success,
            'total_dribbles': total_dribbles,
            'playing_time': playing_time
        }
        self.match_data.append(match)
    def calculate_stats(self):
        """计算统计数据"""
        if not self.match_data:
            return None
        total_matches = len(self.match_data)
        total_chips = sum(match['chips_attempts'] for match in self.match_data)
        total_success = sum(match['chips_success'] for match in self.match_data)
        total_dribbles = sum(match['total_dribbles'] for match in self.match_data)
        # 计算场均数据
        avg_chips = total_chips / total_matches
        avg_success = total_success / total_matches
        # 成功率
        success_rate = (total_success / total_chips * 100) if total_chips > 0 else 0
        # 挑球过人占全部过人的比例
        chips_ratio = (total_chips / total_dribbles * 100) if total_dribbles > 0 else 0
        stats = {
            'total_matches': total_matches,
            'total_chips': total_chips,
            'total_success': total_success,
            'avg_chips_per_match': avg_chips,
            'success_rate': success_rate,
            'chips_ratio': chips_ratio
        }
        return stats
    def judge_frequency(self, stats):
        """判断挑球过人的频率"""
        if not stats:
            return "暂无数据"
        avg_chips = stats['avg_chips_per_match']
        # 根据场均次数判断
        if avg_chips > 8:
            frequency = "非常频繁"
            comment = "该球员非常依赖挑球过人,几乎是每场比赛的常规武器"
        elif avg_chips > 5:
            frequency = "比较频繁"
            comment = "挑球过人是该球员重要的过人方式之一"
        elif avg_chips > 3:
            frequency = "适中"
            comment = "挑球过人使用频率适中,不会过于依赖"
        elif avg_chips > 1:
            frequency = "较少"
            comment = "挑球过人使用较少,更多采用其他过人方式"
        else:
            frequency = "几乎不使用"
            comment = "该球员很少使用挑球过人技术"
        return {
            'frequency': frequency,
            'comment': comment,
            'avg_chips': avg_chips
        }
    def analyze_performance(self):
        """综合分析球员表现"""
        stats = self.calculate_stats()
        if not stats:
            return "暂无数据可分析"
        print(f"\n{'='*50}")
        print(f"球员: {self.player_name}")
        print(f"{'='*50}")
        print(f"总比赛场次: {stats['total_matches']} 场")
        print(f"总挑球过人次数: {stats['total_chips']} 次")
        print(f"总成功次数: {stats['total_success']} 次")
        print(f"场均挑球过人: {stats['avg_chips_per_match']:.1f} 次/场")
        print(f"成功率: {stats['success_rate']:.1f}%")
        print(f"挑球过人占比: {stats['chips_ratio']:.1f}%")
        # 判断频率
        frequency_result = self.judge_frequency(stats)
        print(f"\n频率判断: {frequency_result['frequency']}")
        print(f"分析: {frequency_result['comment']}")
        # 附加分析
        if stats['success_rate'] >= 60:
            print("✅ 成功率很高,挑球过人技术出众")
        elif stats['success_rate'] >= 40:
            print("✅ 成功率尚可,还有提升空间")
        else:
            print("⚠️ 成功率偏低,建议更多练习")
        if stats['chips_ratio'] >= 40:
            print("⚠️ 挑球过人占比较高,对手可能重点防范")
        elif stats['chips_ratio'] >= 25:
            print("✅ 挑球过人是重要技巧但不过度依赖")
        else:
            print("✅ 过人方式多样化")
        return stats
    def best_match(self):
        """找出最佳比赛"""
        if not self.match_data:
            return None
        best_match = max(self.match_data, key=lambda x: x['chips_attempts'])
        return best_match
    def create_chart(self):
        """创建数据可视化图表"""
        if not self.match_data:
            print("暂无数据")
            return
        # 准备数据
        matches = [match['match_id'] for match in self.match_data]
        chips = [match['chips_attempts'] for match in self.match_data]
        success = [match['chips_success'] for match in self.match_data]
        # 创建图表
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
        # 第一个图表:每场挑球过人次数
        ax1.bar(matches, chips, alpha=0.7, color='blue', label='尝试次数')
        ax1.bar(matches, success, alpha=0.7, color='green', label='成功次数')
        ax1.axhline(y=self.threshold, color='red', linestyle='--', label=f'频繁阈值({self.threshold}次)')
        ax1.set_xlabel('比赛场次')
        ax1.set_ylabel('次数')
        ax1.set_title(f'{self.player_name} - 挑球过人次数统计')
        ax1.legend()
        ax1.grid(True, alpha=0.3)
        # 第二个图表:每场成功率和占比
        rates = [match['chips_success']/match['chips_attempts']*100 if match['chips_attempts'] > 0 else 0 
                 for match in self.match_data]
        ratios = [match['chips_attempts']/match['total_dribbles']*100 if match['total_dribbles'] > 0 else 0 
                  for match in self.match_data]
        ax2.plot(matches, rates, marker='o', color='orange', label='成功率 (%)')
        ax2.plot(matches, ratios, marker='s', color='purple', label='占总过人比例 (%)')
        ax2.set_xlabel('比赛场次')
        ax2.set_ylabel('百分比 (%)')
        ax2.set_title(f'{self.player_name} - 挑球过人成功率与占比')
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.savefig('chips_analysis.png', dpi=300, bbox_inches='tight')
        print("\n📊 图表已保存为 'chips_analysis.png'")
        plt.show()
# 主程序
def main():
    print("⚽ 足球挑球过人数据分析系统")
    # 创建球员数据
    player = PlayerData("梅西")
    # 生成模拟数据
    player.generate_sample_data(10)
    # 手动添加一场比赛数据(示例)
    player.add_match_data(
        date=datetime.now(),
        opponent="皇家马德里",
        chips_attempts=12,
        chips_success=8,
        total_dribbles=15,
        playing_time=90
    )
    # 分析表现
    stats = player.analyze_performance()
    # 找出最佳比赛
    best = player.best_match()
    if best:
        print(f"\n🏆 最佳比赛: 第{best['match_id']}场 vs {best['opponent']},尝试{best['chips_attempts']}次,成功{best['chips_success']}次")
    # 分析每一场比赛
    print("\n📋 逐场数据分析:")
    print("-" * 60)
    for match in player.match_data:
        status = "✅" if match['chips_attempts'] > player.threshold else "❌"
        print(f"第{match['match_id']}场 ({match['date'].strftime('%m/%d')}) vs {match['opponent']:20s} "
              f"挑球:{match['chips_attempts']:2d}次 成功:{match['chips_success']:2d}次 {status}")
    # 生成可视化图表(如有matplotlib)
    try:
        player.create_chart()
    except ImportError:
        print("\n⚠️ 未安装matplotlib,跳过图表生成")
    # 最终结论
    print("\n" + "="*50)
    print("📌 最终结论:")
    if stats:
        result = player.judge_frequency(stats)
        print(f"   {result['comment']}")
        print(f"   场均{result['avg_chips']:.1f}次,属于'{result['frequency']}'水平")
if __name__ == "__main__":
    main()

使用方法

安装依赖(可选)

pip install matplotlib

运行程序

python chips_analysis.py

手动添加真实数据

# 创建球员
player = PlayerData("C罗")
# 手动添加多场比赛数据
player.add_match_data(
    date=datetime(2024, 1, 15),
    opponent="皇马",
    chips_attempts=8,
    chips_success=5,
    total_dribbles=12,
    playing_time=90
)

输出示例

==================================================
球员: 梅西
==================================================
总比赛场次: 11 场
总挑球过人次数: 74 次
总成功次数: 45 次
场均挑球过人: 6.7 次/场
成功率: 60.8%
挑球过人占比: 35.4%
频率判断: 比较频繁
分析: 挑球过人是该球员重要的过人方式之一
✅ 成功率很高,挑球过人技术出众
✅ 挑球过人是重要技巧但不过度依赖

这个程序提供了完整的统计数据分析和可视化功能,可以根据场均次数自动判断挑球过人的频率是"非常频繁"还是"几乎不使用"。

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