本文目录导读:

我来帮你设计一个统计传球成功率的Python案例,这里提供几种不同场景的实现方案:
基础版 - 两队简单对比
def calculate_pass_accuracy(team_name, passes_completed, total_passes):
"""计算传球成功率"""
if total_passes == 0:
return 0
accuracy = (passes_completed / total_passes) * 100
return round(accuracy, 2)
def compare_teams(team1, team2):
"""比较两队传球成功率"""
print(f"{'='*50}")
print(f"{'球队':<15}{'成功传球':<10}{'总传球':<10}{'成功率':<10}")
print(f"{'='*50}")
# 输出两队数据
print(f"{team1['name']:<15}{team1['completed']:<10}{team1['total']:<10}"
f"{team1['accuracy']}%")
print(f"{team2['name']:<15}{team2['completed']:<10}{team2['total']:<10}"
f"{team2['accuracy']}%")
print(f"{'='*50}")
# 比较结果
if team1['accuracy'] > team2['accuracy']:
print(f"🏆 {team1['name']} 的传球成功率更高!")
elif team2['accuracy'] > team1['accuracy']:
print(f"🏆 {team2['name']} 的传球成功率更高!")
else:
print("🤝 两队传球成功率相同!")
# 示例数据
team_a = {
'name': '曼联',
'completed': 456,
'total': 520
}
team_b = {
'name': '曼城',
'completed': 489,
'total': 550
}
# 计算成功率
team_a['accuracy'] = calculate_pass_accuracy(team_a['name'],
team_a['completed'],
team_a['total'])
team_b['accuracy'] = calculate_pass_accuracy(team_b['name'],
team_b['completed'],
team_b['total'])
# 比较结果
compare_teams(team_a, team_b)
进阶版 - 多项传球指标分析
class FootballTeam:
"""足球队伍类"""
def __init__(self, name, passes_data):
self.name = name
self.passes_data = passes_data # 字典: {'successful': 成功数, 'total': 总数}
def get_accuracy(self):
"""获取传球成功率"""
successful = self.passes_data['successful']
total = self.passes_data['total']
return (successful / total * 100) if total > 0 else 0
def analyze_passes(teams):
"""分析多支球队的传球数据"""
results = []
for team in teams:
accuracy = team.get_accuracy()
results.append({
'team': team.name,
'accuracy': accuracy,
'successful': team.passes_data['successful'],
'total': team.passes_data['total']
})
# 排序
results.sort(key=lambda x: x['accuracy'], reverse=True)
# 显示结果
print(f"\n{'='*60}")
print(f"{'排名':<5}{'球队':<15}{'成功传球':<10}{'总传球':<10}{'成功率':<10}")
print(f"{'='*60}")
for i, result in enumerate(results, 1):
print(f"{i:<5}{result['team']:<15}{result['successful']:<10}"
f"{result['total']:<10}{result['accuracy']:.2f}%")
print(f"{'='*60}")
# 找出最高和最低
best = results[0]
worst = results[-1]
print(f"\n📊 最佳传球成功率: {best['team']} {best['accuracy']:.2f}%")
print(f"📊 最低传球成功率: {worst['team']} {worst['accuracy']:.2f}%")
return results
# 示例数据
teams_data = [
FootballTeam("巴塞罗那", {'successful': 523, 'total': 567}),
FootballTeam("皇家马德里", {'successful': 498, 'total': 545}),
FootballTeam("拜仁慕尼黑", {'successful': 512, 'total': 560}),
FootballTeam("利物浦", {'successful': 456, 'total': 520}),
FootballTeam("国际米兰", {'successful': 445, 'total': 510}),
]
# 执行分析
results = analyze_passes(teams_data)
完整版 - 带数据输入和图表可视化
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def create_football_stats():
"""创建足球传球统计系统"""
def get_team_data():
"""获取球队数据"""
teams = []
print("请输入球队数据(输入'完成'结束):")
while True:
team_name = input("球队名称: ").strip()
if team_name.lower() == '完成' or team_name.lower() == 'quit':
break
try:
successful = int(input(f"{team_name} 成功传球数: "))
total = int(input(f"{team_name} 总传球数: "))
if successful > total:
print("错误:成功传球数不能大于总传球数!")
continue
teams.append({
'name': team_name,
'successful': successful,
'total': total,
'accuracy': (successful / total * 100) if total > 0 else 0
})
print(f"✅ {team_name} 数据已添加")
except ValueError:
print("❌ 请输入有效数字!")
return teams
def visualize_data(teams):
"""可视化传球数据"""
if not teams:
print("没有数据可以展示")
return
names = [team['name'] for team in teams]
accuracy = [team['accuracy'] for team in teams]
successful = [team['successful'] for team in teams]
total = [team['total'] for team in teams]
# 创建图表
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('足球传球统计分析', fontsize=16)
# 1. 传球成功率柱状图
axes[0, 0].bar(names, accuracy, color=['red', 'blue', 'green', 'orange', 'purple'][:len(names)])
axes[0, 0].set_title('传球成功率 (%)')
axes[0, 0].set_ylabel('百分比')
axes[0, 0].tick_params(axis='x', rotation=45)
# 2. 成功传球数
axes[0, 1].bar(names, successful, color='green', alpha=0.7)
axes[0, 1].set_title('成功传球数')
axes[0, 1].set_ylabel('次数')
axes[0, 1].tick_params(axis='x', rotation=45)
# 3. 饼图 - 各队成功传球占比
axes[1, 0].pie(successful, labels=names, autopct='%1.1f%%')
axes[1, 0].set_title('成功传球占比')
# 4. 散点图 - 传球数与成功率关系
axes[1, 1].scatter(total, accuracy, s=100)
for i, name in enumerate(names):
axes[1, 1].annotate(name, (total[i], accuracy[i]))
axes[1, 1].set_xlabel('总传球数')
axes[1, 1].set_ylabel('成功率 (%)')
axes[1, 1].set_title('传球数 vs 成功率')
plt.tight_layout()
plt.show()
def analyze_and_compare(teams):
"""分析并比较数据"""
if not teams:
print("没有数据可分析")
return
# 创建DataFrame便于分析
df = pd.DataFrame(teams)
# 统计数据
print("\n" + "="*60)
print("📊 传球数据统计报告")
print("="*60)
print("\n详细数据:")
print(df[['name', 'successful', 'total', 'accuracy']].to_string(index=False))
print(f"\n🔍 统计信息:")
print(f"平均成功率: {df['accuracy'].mean():.2f}%")
print(f"最高成功率: {df.loc[df['accuracy'].idxmax(), 'name']} "
f"({df['accuracy'].max():.2f}%)")
print(f"最低成功率: {df.loc[df['accuracy'].idxmin(), 'name']} "
f"({df['accuracy'].min():.2f}%)")
# 判断哪队更高
max_team = df.loc[df['accuracy'].idxmax()]
print(f"\n🏆 胜出球队: {max_team['name']} "
f"(成功率: {max_team['accuracy']:.2f}%)")
return df
# 主程序流程
print("⚽ 足球传球成功率统计系统 ⚽")
print("="*60)
# 获取数据
teams = get_team_data()
if teams:
# 分析数据
df = analyze_and_compare(teams)
# 询问是否可视化
show_chart = input("\n是否显示图表?(y/n): ").lower()
if show_chart == 'y':
visualize_data(teams)
else:
print("未输入任何数据,程序结束。")
# 运行程序
if __name__ == "__main__":
create_football_stats()
简洁对比版 - 两队直接比较
def compare_two_teams(team1_name, team1_success, team1_total,
team2_name, team2_success, team2_total):
"""简洁版两队对比"""
# 计算成功率
acc1 = (team1_success / team1_total * 100) if team1_total > 0 else 0
acc2 = (team2_success / team2_total * 100) if team2_total > 0 else 0
# 显示结果
print(f"""
{'='*50}
传球数据对比
{'='*50}
{team1_name}: {team1_success}/{team1_total} = {acc1:.1f}%
{team2_name}: {team2_success}/{team2_total} = {acc2:.1f}%
{'='*50}
""")
# 判定结果
if acc1 > acc2:
result = f"🏆 {team1_name} 获胜!"
elif acc2 > acc1:
result = f"🏆 {team2_name} 获胜!"
else:
result = "🤝 平局"
print(f"结果: {result}")
print(f"成功率差值: {abs(acc1 - acc2):.2f}%")
return max(acc1, acc2)
# 使用示例
if __name__ == "__main__":
# 手动输入
compare_two_teams("阿森纳", 432, 480, "切尔西", 421, 475)
# 或者让用户输入
print("请输入球队1数据:")
name1 = input("球队名: ")
suc1 = int(input("成功传球: "))
tot1 = int(input("总传球: "))
print("请输入球队2数据:")
name2 = input("球队名: ")
suc2 = int(input("成功传球: "))
tot2 = int(input("总传球: "))
compare_two_teams(name1, suc1, tot1, name2, suc2, tot2)
使用建议
- 基础版:适合快速了解两家俱乐部的对比
- 进阶版:适合同时比较多支球队
- 可视化版:需要安装
matplotlib和pandas:pip install matplotlib pandas
- 简洁版:最轻量级,适合快速计算
每个版本都能有效地比较两队或多队的传球成功率,你可以根据实际需求选择合适的版本使用。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播