本文目录导读:

我来提供几个不同版本的足球射门统计Python案例,从简单到复杂:
版本1:基础版(字典统计)
# 足球射门次数统计 - 基础版
def basic_shots_statistics():
# 模拟一场比赛的射门数据
# 每行数据格式: (球队, 球员, 是否射正)
match_data = [
("主队", "球员1", True),
("客队", "球员A", False),
("主队", "球员2", True),
("主队", "球员3", False),
("客队", "球员B", True),
("客队", "球员C", False),
("主队", "球员1", True),
("客队", "球员A", True),
("主队", "球员4", False),
("客队", "球员B", False),
]
# 统计各队射门次数
shots = {}
shots_on_target = {}
for team, player, on_target in match_data:
# 统计射门次数
shots[team] = shots.get(team, 0) + 1
# 统计射正次数
if on_target:
shots_on_target[team] = shots_on_target.get(team, 0) + 1
# 输出结果
print("=== 射门统计 ===")
for team in shots:
print(f"{team}:")
print(f" 总射门: {shots[team]}次")
print(f" 射正: {shots_on_target.get(team, 0)}次")
print(f" 射偏: {shots[team] - shots_on_target.get(team, 0)}次")
print()
# 比较哪队射门更多
if shots["主队"] > shots["客队"]:
print(f"主队射门更多,多{shots['主队'] - shots['客队']}次")
elif shots["主队"] < shots["客队"]:
print(f"客队射门更多,多{shots['客队'] - shots['主队']}次")
else:
print("两队射门次数相同")
if __name__ == "__main__":
basic_shots_statistics()
版本2:面向对象版(更专业)
import random
from collections import defaultdict
class FootballMatch:
"""足球比赛射门统计类"""
def __init__(self, home_team="主队", away_team="客队"):
self.home_team = home_team
self.away_team = away_team
self.shots_data = []
self.team_players = {}
self._setup_teams()
def _setup_teams(self):
"""设置球队球员"""
self.team_players[self.home_team] = [
f"前锋{i}" for i in range(1, 4)
] + [f"中场{i}" for i in range(1, 4)] + [f"后卫{i}" for i in range(1, 4)]
self.team_players[self.away_team] = [
f"前锋{i}" for i in range(1, 4)
] + [f"中场{i}" for i in range(1, 4)] + [f"后卫{i}" for i in range(1, 4)]
def simulate_shots(self, home_shots=15, away_shots=12):
"""模拟射门数据"""
for team, num_shots in [(self.home_team, home_shots),
(self.away_team, away_shots)]:
for _ in range(num_shots):
player = random.choice(self.team_players[team])
on_target = random.random() < 0.35 # 35%射正率
minute = random.randint(1, 90)
self.shots_data.append({
'team': team,
'player': player,
'on_target': on_target,
'minute': minute
})
self.shots_data.sort(key=lambda x: x['minute'])
def get_statistics(self):
"""获取统计数据"""
stats = defaultdict(lambda: {'shots': 0, 'on_target': 0})
for shot in self.shots_data:
team = shot['team']
stats[team]['shots'] += 1
if shot['on_target']:
stats[team]['on_target'] += 1
return stats
def display_statistics(self):
"""显示统计结果"""
print(f"\n{'='*50}")
print(f"比赛:{self.home_team} VS {self.away_team}")
print(f"{'='*50}")
stats = self.get_statistics()
for team in [self.home_team, self.away_team]:
team_stats = stats[team]
print(f"\n{team}:")
print(f" 总射门: {team_stats['shots']}次")
print(f" 射正: {team_stats['on_target']}次")
print(f" 射偏: {team_stats['shots']} - {team_stats['on_target']} = {team_stats['shots'] - team_stats['on_target']}次")
print(f" 射正率: {team_stats['on_target']/team_stats['shots']*100:.1f}%")
# 比较射门次数
home = stats[self.home_team]['shots']
away = stats[self.away_team]['shots']
print(f"\n{'='*50}")
if home > away:
print(f"🏆 {self.home_team}射门更多,多{home-away}次")
print(f"📊 射门比:{home} : {away}")
elif home < away:
print(f"🏆 {self.away_team}射门更多,多{away-home}次")
print(f"📊 射门比:{home} : {away}")
else:
print("🤝 两队射门次数相同")
print(f"📊 射门比:{home} : {away}")
print(f"{'='*50}")
# 测试
def test_football_match():
match = FootballMatch("巴塞罗那", "皇家马德里")
match.simulate_shots(home_shots=15, away_shots=12)
match.display_statistics()
# 显示射门时间分布
print("\n射门时间分布(前10次射门):")
for i, shot in enumerate(match.shots_data[:10], 1):
target = "✓ 射正" if shot['on_target'] else "✗ 射偏"
print(f" {i}. {shot['minute']}分钟 - {shot['team']} - {shot['player']} - {target}")
if __name__ == "__main__":
test_football_match()
版本3:数据可视化版(带图表)
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
def visualize_shots_statistics():
"""带数据可视化的射门统计"""
# 模拟数据
matches_data = {
"英超": [
("曼联", "利物浦", 14, 11),
("曼城", "阿森纳", 16, 13),
("切尔西", "热刺", 12, 15),
("纽卡斯尔", "维拉", 10, 8),
],
"西甲": [
("皇马", "巴萨", 13, 16),
("马竞", "塞维利亚", 11, 9),
("皇家社会", "贝蒂斯", 9, 12),
],
"意甲": [
("尤文", "国米", 12, 14),
("米兰", "那不勒斯", 15, 10),
("罗马", "拉齐奥", 13, 11),
],
}
# 统计数据
teams_aggregate = defaultdict(lambda: {'shots': 0, 'matches': 0})
league_data = defaultdict(lambda: {'total_shots': 0, 'matches': 0})
for league, matches in matches_data.items():
for home, away, home_shots, away_shots in matches:
# 统计各队数据
teams_aggregate[home]['shots'] += home_shots
teams_aggregate[home]['matches'] += 1
teams_aggregate[away]['shots'] += away_shots
teams_aggregate[away]['matches'] += 1
# 统计联赛数据
league_data[league]['total_shots'] += home_shots + away_shots
league_data[league]['matches'] += 1
# 创建图表
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle('足球射门数据统计', fontsize=16)
# 1. 各队场均射门
ax1 = axes[0, 0]
teams = sorted(teams_aggregate.keys(),
key=lambda x: teams_aggregate[x]['shots']/teams_aggregate[x]['matches'],
reverse=True)
avg_shots = [teams_aggregate[team]['shots']/teams_aggregate[team]['matches']
for team in teams]
bars = ax1.bar(teams, avg_shots, color='skyblue', edgecolor='navy')
ax1.set_title('各队场均射门次数', fontsize=12)
ax1.set_ylabel('场均射门')
ax1.set_ylim(0, max(avg_shots) + 2)
for bar, val in zip(bars, avg_shots):
ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.2,
f'{val:.1f}', ha='center', va='bottom')
# 2. 联赛总射门对比
ax2 = axes[0, 1]
leagues = list(league_data.keys())
total_shots = [league_data[lg]['total_shots'] for lg in leagues]
pie_colors = ['#ff9999', '#66b3ff', '#99ff99']
ax2.pie(total_shots, labels=leagues, autopct='%1.1f%%',
colors=pie_colors, startangle=90)
ax2.set_title('各联赛总射门占比', fontsize=12)
# 3. 单场比赛射门对比
ax3 = axes[1, 0]
match_names = []
home_values = []
away_values = []
for league, matches in matches_data.items():
for home, away, home_shots, away_shots in matches:
match_names.append(f'{home[:4]} vs {away[:4]}')
home_values.append(home_shots)
away_values.append(away_shots)
x = np.arange(len(match_names))
width = 0.35
bars1 = ax3.bar(x - width/2, home_values, width, label='主队', color='green', alpha=0.7)
bars2 = ax3.bar(x + width/2, away_values, width, label='客队', color='red', alpha=0.7)
ax3.set_title('各场次射门对比', fontsize=12)
ax3.set_xticks(x)
ax3.set_xticklabels(match_names, rotation=45, ha='right')
ax3.set_ylabel('射门次数')
ax3.legend()
# 4. 射门次数分布
ax4 = axes[1, 1]
all_shots = []
for league, matches in matches_data.items():
for home, away, home_shots, away_shots in matches:
all_shots.append(home_shots)
all_shots.append(away_shots)
ax4.hist(all_shots, bins=10, edgecolor='black', alpha=0.7, color='orange')
ax4.set_title('射门次数分布', fontsize=12)
ax4.set_xlabel('射门次数')
ax4.set_ylabel('场次')
plt.tight_layout()
plt.show()
# 输出文字统计
print("\n=== 统计报告 ===")
print("\n1. 场均射门排名(前5):")
for i, team in enumerate(teams[:5], 1):
print(f" {i}. {team}: {avg_shots[teams.index(team)]:.1f}次/场")
print("\n2. 单场射门记录:")
max_shots = max(all_shots)
print(f" 最高单场射门:{max_shots}次")
print("\n3. 各联赛射门总数:")
for league in leagues:
print(f" {league}: {league_data[league]['total_shots']}次")
if __name__ == "__main__":
visualize_shots_statistics()
版本4:文件处理版(从文件读取数据)
import csv
import json
from collections import defaultdict
def read_data_from_file(file_path):
"""从文件读取射门数据"""
shots_data = []
if file_path.endswith('.csv'):
with open(file_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
shots_data.append(row)
elif file_path.endswith('.json'):
with open(file_path, 'r', encoding='utf-8') as f:
shots_data = json.load(f)
else:
raise ValueError("不支持的文件格式,请使用.csv或.json")
return shots_data
def analyze_shots_from_file(file_path):
"""分析文件中的射门数据"""
try:
shots_data = read_data_from_file(file_path)
# 统计各队射门
team_stats = defaultdict(lambda: {'shots': 0, 'on_target': 0})
for shot in shots_data:
team = shot['team']
team_stats[team]['shots'] += 1
if shot.get('on_target', False):
team_stats[team]['on_target'] += 1
# 输出结果
print(f"\n从文件 {file_path} 读取到 {len(shots_data)} 条射门记录")
print("\n=== 射门统计结果 ===")
teams = list(team_stats.keys())
if len(teams) >= 2:
team1, team2 = teams[0], teams[1]
if team_stats[team1]['shots'] > team_stats[team2]['shots']:
print(f"🏆 {team1}射门更多,共{team_stats[team1]['shots']}次")
elif team_stats[team1]['shots'] < team_stats[team2]['shots']:
print(f"🏆 {team2}射门更多,共{team_stats[team2]['shots']}次")
else:
print("两队射门次数相同")
return team_stats
except FileNotFoundError:
print(f"错误:文件 {file_path} 不存在")
return None
except Exception as e:
print(f"读取文件时出错:{e}")
return None
# 创建示例数据文件
def create_sample_data():
"""创建示例数据文件"""
sample_data = [
{"team": "主队", "player": "前锋1", "on_target": True, "minute": 15},
{"team": "客队", "player": "前锋A", "on_target": False, "minute": 23},
{"team": "主队", "player": "中场2", "on_target": False, "minute": 35},
{"team": "客队", "player": "前锋B", "on_target": True, "minute": 42},
{"team": "主队", "player": "前锋1", "on_target": True, "minute": 58},
{"team": "客队", "player": "中场C", "on_target": False, "minute": 66},
{"team": "主队", "player": "后卫3", "on_target": False, "minute": 74},
{"team": "客队", "player": "前锋A", "on_target": True, "minute": 82},
{"team": "主队", "player": "前锋2", "on_target": False, "minute": 85},
{"team": "客队", "player": "前锋B", "on_target": True, "minute": 90},
]
# 保存为JSON
with open('shots_data.json', 'w', encoding='utf-8') as f:
json.dump(sample_data, f, ensure_ascii=False, indent=2)
print("已创建示例数据文件:shots_data.json")
if __name__ == "__main__":
# 创建示例数据
create_sample_data()
# 分析数据
stats = analyze_shots_from_file('shots_data.json')
if stats:
print("\n详细统计:")
for team, data in stats.items():
print(f" {team}: 射门{data['shots']}次,射正{data['on_target']}次")
使用方法
- 基础版:适合学习Python字典和基本统计
- 面向对象版:模拟完整比赛,包含球员、时间等详细数据
- 可视化版:需要安装matplotlib,展示专业图表
- 文件处理版:从外部文件读取数据,适合实际应用
运行任一版本都会输出"哪队射门更多"的结果,并附带详细的统计数据,你可以根据需要选择合适的版本使用!