python案例统计脚后跟传球成功几次?

wen python案例 2

本文目录导读:

python案例统计脚后跟传球成功几次?

  1. 方案一:手动输入统计
  2. 方案二:模拟比赛数据
  3. 方案三:基于视频/日志分析
  4. 使用方法
  5. 运行示例

我来帮你创建一个统计脚后跟传球成功次数的Python程序,这个程序可以通过模拟或手动输入数据来统计。

手动输入统计

class HeelPassTracker:
    def __init__(self):
        self.attempts = []  # 存储每次尝试的记录
        self.total_attempts = 0
        self.successful_passes = 0
    def record_pass(self, success):
        """记录一次脚后跟传球
        Args:
            success: bool, True表示成功,False表示失败
        """
        self.total_attempts += 1
        self.attempts.append(success)
        if success:
            self.successful_passes += 1
    def get_stats(self):
        """获取统计数据"""
        success_rate = (self.successful_passes / self.total_attempts * 100) 
        if self.total_attempts > 0 else 0
        return {
            'total_attempts': self.total_attempts,
            'successful': self.successful_passes,
            'failed': self.total_attempts - self.successful_passes,
            'success_rate': f"{success_rate:.1f}%"
        }
    def clear(self):
        """清除所有记录"""
        self.attempts.clear()
        self.total_attempts = 0
        self.successful_passes = 0
# 使用示例
def main():
    tracker = HeelPassTracker()
    print("=== 脚后跟传球统计系统 ===")
    print("输入 'y' 表示成功,'n' 表示失败,'q' 退出查看统计")
    while True:
        user_input = input("\n这次传球成功了吗?(y/n/q): ").lower()
        if user_input == 'q':
            break
        elif user_input == 'y':
            tracker.record_pass(True)
            print("✓ 记录成功!")
        elif user_input == 'n':
            tracker.record_pass(False)
            print("✗ 记录失败")
        else:
            print("请输入 y、n 或 q")
    stats = tracker.get_stats()
    print("\n=== 统计结果 ===")
    for key, value in stats.items():
        print(f"{key}: {value}")
if __name__ == "__main__":
    main()

模拟比赛数据

import random
from datetime import datetime
class MatchHeelPassAnalyzer:
    def __init__(self):
        self.pass_data = []
    def simulate_match(self, opponent="对手", minutes=90, attempts=15):
        """模拟一场比赛
        Args:
            opponent: str, 对手名称
            minutes: int, 比赛分钟数
            attempts: int, 尝试脚后跟传球次数
        """
        match_data = {
            'opponent': opponent,
            'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
            'passes': []
        }
        for _ in range(attempts):
            # 70% 的成功率(可以调整)
            success_probability = random.random() < 0.7
            # 随机分布在比赛时间中
            minute = random.randint(1, minutes)
            match_data['passes'].append({
                'minute': minute,
                'success': success_probability
            })
        self.pass_data.append(match_data)
        return match_data
    def analyze_success_rate(self):
        """分析总成功率"""
        total = 0
        success = 0
        for match in self.pass_data:
            for pass_attempt in match['passes']:
                total += 1
                if pass_attempt['success']:
                    success += 1
        return (success, total, success/total*100 if total else 0)
    def print_analysis(self):
        """打印详细分析"""
        print("="*50)
        print("脚后跟传球统计分析")
        print("="*50)
        success_count, total_count, rate = self.analyze_success_rate()
        if self.pass_data:
            for index, match in enumerate(self.pass_data, 1):
                match_success = sum(1 for p in match['passes'] if p['success'])
                match_total = len(match['passes'])
                print(f"\n第{index}场 ({match['opponent']}):")
                print(f"  传球次数: {match_total}")
                print(f"  成功次数: {match_success}")
                print(f"  成功率: {match_success/match_total*100:.1f}%")
                print(f"  时间分布: {[f\"{p['minute']}min {'✓' if p['success'] else '✗'}\" for p in match['passes']]}")
        print(f"\n总计统计:")
        print(f"  总尝试次数: {total_count}")
        print(f"  总成功次数: {success_count}")
        print(f"  总成功率: {rate:.1f}%")
# 模拟示例
def simulate_example():
    analyzer = MatchHeelPassAnalyzer()
    # 模拟3场比赛
    analyzer.simulate_match("皇家马德里", attempts=10)
    analyzer.simulate_match("巴塞罗那", attempts=12)
    analyzer.simulate_match("曼城", attempts=8)
    analyzer.print_analysis()
if __name__ == "__main__":
    simulate_example()

基于视频/日志分析

import re
from collections import defaultdict
class VideoHeelPassAnalyzer:
    def __init__(self):
        self.actions = []
        self.player_stats = defaultdict(lambda: {'成功': 0, '失败': 0, '总数': 0})
    def load_from_log(self, log_file):
        """从日志文件加载数据
        日志格式: 
        pass 分钟 球员 成功/失败
         pass 23 梅西 成功
        """
        try:
            with open(log_file, 'r', encoding='utf-8') as file:
                for line in file:
                    line = line.strip()
                    if line.startswith('heel_pass') or line.startswith('hip_pass'):
                        parts = line.split()
                        if len(parts) >= 4:
                            action = {
                                'time': parts[1],
                                'player': parts[2],
                                'success': parts[3].lower() in ['成功', 'success', 'true', 'ok']
                            }
                            self.actions.append(action)
                            player = action['player']
                            if action['success']:
                                self.player_stats[player]['成功'] += 1
                            else:
                                self.player_stats[player]['失败'] += 1
                            self.player_stats[player]['总数'] += 1
        except FileNotFoundError:
            print(f"文件 {log_file} 不存在")
    def add_manual_action(self, player, success):
        """手动添加一次动作"""
        action = {
            'time': len(self.actions) + 1,
            'player': player,
            'success': success
        }
        self.actions.append(action)
        if success:
            self.player_stats[player]['成功'] += 1
            self.player_stats[player]['总数'] += 1
        else:
            self.player_stats[player]['失败'] += 1
            self.player_stats[player]['总数'] += 1
    def analyze(self):
        """分析数据"""
        print("\n=== 脚后跟传球统计 ===")
        print(f"总次数: {len(self.actions)}")
        success = sum(1 for a in self.actions if a['success'])
        print(f"成功次数: {success}")
        print(f"失败次数: {len(self.actions) - success}")
        print(f"成功率: {(success/len(self.actions)*100):.1f}%")
        # 按球员统计
        print("\n--- 球员统计 ---")
        for player, stats in sorted(self.player_stats.items()):
            rate = stats['成功']/stats['总数']*100 if stats['总数'] > 0 else 0
            print(f"{player}: 成功{stats['成功']}次, 失败{stats['失败']}次, 共{stats['总数']}次, 成功率{rate:.1f}%")
# 使用示例
def analyze_from_log():
    analyzer = VideoHeelPassAnalyzer()
    # 模拟一些数据
    sample_data = """heel_pass 5 梅西 成功
heel_pass 12 姆巴佩 失败
heel_pass 18 内马尔 成功
heel_pass 23 梅西 失败
heel_pass 45 梅西 成功
heel_pass 67 姆巴佩 成功
heel_pass 78 内马尔 成功
heel_pass 82 梅西 失败
heel_pass 85 姆巴佩 成功
heel_pass 90 梅西 成功"""
    # 写入临时文件
    with open("match_log.txt", "w", encoding="utf-8") as f:
        f.write(sample_data)
    analyzer.load_from_log("match_log.txt")
    analyzer.analyze()
if __name__ == "__main__":
    analyze_from_log()

使用方法

  1. 实时统计:使用方案一,适合现场记录
  2. 模拟分析:使用方案二,用于数据分析
  3. 日志分析:使用方案三,处理大量历史数据

运行示例

# 运行手动统计
python heel_pass_tracker.py
# 运行模拟分析  
python heel_pass_mock_analysis.py

这些程序可以帮助你:

  • 记录每一次脚后跟传球
  • 统计成功率和次数
  • 按时间、球员等因素分析
  • 生成统计数据

根据你的具体使用场景选择合适的方法!

上一篇python案例统计犯规战术阻止反击几次?

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

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