python案例统计快发任意球尝试几次?

wen python案例 4

本文目录导读:

python案例统计快发任意球尝试几次?

  1. 方案1:基础版(简单统计)
  2. 方案2:进阶版(带时间记录和场景分析)
  3. 方案3:交互式版本
  4. 使用建议

我来帮你创建一个统计快发任意球尝试次数的Python案例。

方案1:基础版(简单统计)

class FreeKickCounter:
    def __init__(self):
        self.attempts = []  # 存储每次尝试的记录
        self.total_attempts = 0
        self.successful_attempts = 0
        self.failed_attempts = 0
    def add_attempt(self, is_successful=False, description=""):
        """添加一次快发任意球尝试"""
        self.total_attempts += 1
        if is_successful:
            self.successful_attempts += 1
        else:
            self.failed_attempts += 1
        # 记录详细信息
        attempt_record = {
            'number': self.total_attempts,
            'success': is_successful,
            'description': description
        }
        self.attempts.append(attempt_record)
        return f"第{self.total_attempts}次尝试已记录"
    def get_statistics(self):
        """获取统计数据"""
        return {
            '总计次数': self.total_attempts,
            '成功次数': self.successful_attempts,
            '失败次数': self.failed_attempts,
            '成功率': f"{self.successful_attempts/self.total_attempts*100:.1f}%" if self.total_attempts > 0 else "0%"
        }
    def display_statistics(self):
        """显示统计数据"""
        print("=" * 50)
        print("快发任意球统计")
        print("=" * 50)
        stats = self.get_statistics()
        for key, value in stats.items():
            print(f"{key}: {value}")
        print("=" * 50)
# 使用示例
def main():
    counter = FreeKickCounter()
    # 模拟一些尝试
    counter.add_attempt(True, "快速发出,射门得分")
    counter.add_attempt(False, "被裁判阻止")
    counter.add_attempt(True, "传给队友,形成单刀")
    counter.add_attempt(False, "发球违例")
    counter.add_attempt(True, "快速发出,制造威胁")
    counter.display_statistics()
    # 显示详细记录
    print("\n详细记录:")
    for attempt in counter.attempts:
        status = "✓" if attempt['success'] else "✗"
        print(f"{attempt['number']}. [{status}] {attempt['description']}")
main()

方案2:进阶版(带时间记录和场景分析)

import time
from datetime import datetime
from collections import Counter
class AdvancedFreeKickCounter:
    def __init__(self):
        self.attempts = []
    def add_attempt(self, result, location="", time_point="", notes=""):
        """
        添加一次尝试记录
        result: 'success' 或 'fail'
        location: 发球位置
        time_point: 比赛时间段
        """
        attempt = {
            'timestamp': datetime.now(),
            'result': result,
            'location': location,
            'time_point': time_point,
            'notes': notes,
            'id': len(self.attempts) + 1
        }
        self.attempts.append(attempt)
        return f"记录成功 (ID: {attempt['id']})"
    def get_total_attempts(self):
        return len(self.attempts)
    def get_success_rate(self):
        if not self.attempts:
            return 0
        successes = sum(1 for a in self.attempts if a['result'] == 'success')
        return (successes / len(self.attempts)) * 100
    def get_location_analysis(self):
        """按位置分析"""
        locations = Counter()
        for attempt in self.attempts:
            locations[attempt['location']] += 1
        return dict(locations)
    def get_time_analysis(self):
        """按时间段分析"""
        time_stats = Counter()
        for attempt in self.attempts:
            time_stats[attempt['time_point']] += 1
        return dict(time_stats)
    def generate_report(self):
        """生成完整报告"""
        print("\n" + "="*60)
        print("快发任意球完整分析报告")
        print("="*60)
        print(f"总尝试次数: {self.get_total_attempts()}")
        print(f"成功率: {self.get_success_rate():.1f}%")
        # 位置分析
        print("\n按位置统计:")
        for location, count in self.get_location_analysis().items():
            print(f"  {location}: {count}次")
        # 时间分析
        print("\n按时间段统计:")
        for time_point, count in self.get_time_analysis().items():
            print(f"  {time_point}: {count}次")
        # 显示详细记录
        print("\n详细记录:")
        for attempt in self.attempts:
            result = "✓成功" if attempt['result'] == 'success' else "✗失败"
            print(f"  ID:{attempt['id']:2d} | {result} | 位置:{attempt['location']} | 时间:{attempt['time_point']} | 备注:{attempt['notes']}")
        print("="*60)
# 使用示例
def advanced_main():
    counter = AdvancedFreeKickCounter()
    # 添加一些示例数据
    counter.add_attempt('success', '前场右路', '上半场', '快速发球,队友跟进射门')
    counter.add_attempt('fail', '中场', '下半场', '被裁判判罚')
    counter.add_attempt('success', '前场左路', '上半场', '直接射门命中')
    counter.add_attempt('success', '前场中路', '补时阶段', '快速配合成功')
    counter.add_attempt('fail', '后场', '上半场', '发球失误')
    counter.add_attempt('success', '前场左路', '下半场', '传中制造威胁')
    counter.generate_report()
advanced_main()

方案3:交互式版本

def interactive_counter():
    """交互式快发任意球统计程序"""
    attempts = []
    def display_menu():
        print("\n" + "="*40)
        print("快发任意球统计系统")
        print("="*40)
        print("1. 添加成功尝试")
        print("2. 添加失败尝试")
        print("3. 查看统计")
        print("4. 查看详细记录")
        print("5. 清空所有记录")
        print("0. 退出")
        return input("请选择操作: ")
    while True:
        choice = display_menu()
        if choice == '1':
            desc = input("请输入成功描述: ")
            attempts.append({'result': 'success', 'desc': desc})
            print("已记录一次成功尝试!")
        elif choice == '2':
            desc = input("请输入失败描述: ")
            attempts.append({'result': 'fail', 'desc': desc})
            print("已记录一次失败尝试!")
        elif choice == '3':
            total = len(attempts)
            if total == 0:
                print("\n还没有尝试记录")
                continue
            success = sum(1 for a in attempts if a['result'] == 'success')
            fail = total - success
            rate = (success / total) * 100
            print(f"\n📊 统计结果:")
            print(f"总尝试: {total}次")
            print(f"成功: {success}次")
            print(f"失败: {fail}次")
            print(f"成功率: {rate:.1f}%")
        elif choice == '4':
            if not attempts:
                print("\n暂无记录")
                continue
            print("\n详细记录:")
            for i, attempt in enumerate(attempts, 1):
                result = "✓" if attempt['result'] == 'success' else "✗"
                print(f"{i:2d}. [{result}] {attempt['desc']}")
        elif choice == '5':
            attempts.clear()
            print("已清空所有记录")
        elif choice == '0':
            print("感谢使用,再见!")
            break
        else:
            print("无效选择,请重试")
# 运行交互式程序
# interactive_counter()
# 或者直接运行示例
if __name__ == "__main__":
    print("方案1运行结果:")
    main()
    print("\n" + "="*50)
    print("方案2运行结果:")
    advanced_main()

使用建议

  1. 基础版适用于简单的统计需求
  2. 进阶版适合需要详细分析(位置、时间段等)的场景
  3. 交互式版本适合实时手动记录

你可以根据实际需求选择使用哪个版本,如果需要更多自定义功能(如导出Excel、图表展示等),我可以进一步帮你扩展。

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