本文目录导读:

我来帮你创建一个统计足球比赛中反越位成功形成单刀次数的Python案例。
简单手动统计
def count_offside_trap_and_one_on_one(matches_data):
"""
统计反越位成功形成单刀的次数
参数:
matches_data: 包含比赛事件的列表
返回:
反越位成功形成单刀的次数
"""
counter = 0
for match in matches_data:
for event in match['events']:
# 判断条件:反越位成功 + 形成单刀
if (event['type'] == 'offside_trap' and
event['result'] == 'successful' and
event['follow_up'] == 'one_on_one'):
counter += 1
print(f"比赛{match['id']}: 第{event['minute']}分钟, "
f"球员{event['player']}反越位成功形成单刀")
return counter
# 示例数据
matches = [
{
'id': 1,
'teams': ['曼城', '阿森纳'],
'events': [
{'minute': 23, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '哈兰德', 'team': '曼城'},
{'minute': 45, 'type': 'shot', 'result': 'goal', 'player': '萨卡'},
{'minute': 67, 'type': 'offside_trap', 'result': 'failed',
'follow_up': None, 'player': '热苏斯'},
]
},
{
'id': 2,
'teams': ['皇马', '巴萨'],
'events': [
{'minute': 15, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '姆巴佩', 'team': '皇马'},
{'minute': 78, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '莱万', 'team': '巴萨'},
{'minute': 88, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'corner', 'player': '维尼修斯'},
]
}
]
# 执行统计
result = count_offside_trap_and_one_on_one(matches)
print(f"\n总共反越位成功形成单刀次数: {result}次")
更完整的足球事件分析系统
import json
from datetime import datetime
from typing import List, Dict, Any
class FootballEventAnalyzer:
"""足球比赛事件分析器"""
def __init__(self):
self.offside_trap_goals = 0
self.events_log = []
def analyze_match(self, match_data: Dict[str, Any]) -> Dict:
"""分析单场比赛"""
match_stats = {
'match_id': match_data.get('id'),
'teams': match_data.get('teams', []),
'total_offside_traps': 0,
'successful_offside_traps': 0,
'one_on_one_chances': 0,
'converted_goals': 0
}
for event in match_data.get('events', []):
# 统计反越位情况
if event.get('type') == 'offside_trap':
match_stats['total_offside_traps'] += 1
if event.get('result') == 'successful':
match_stats['successful_offside_traps'] += 1
# 判断是否形成单刀
if event.get('follow_up') == 'one_on_one':
match_stats['one_on_one_chances'] += 1
# 判断是否转化为进球
if event.get('scored'):
match_stats['converted_goals'] += 1
self.offside_trap_goals += 1
# 记录详细日志
log_entry = {
'time': event.get('minute'),
'player': event.get('player'),
'team': event.get('team'),
'scored': event.get('scored', False),
'opponent_goalkeeper': event.get('goalkeeper')
}
self.events_log.append(log_entry)
return match_stats
def analyze_multiple_matches(self, matches: List[Dict]) -> Dict:
"""分析多场比赛"""
all_stats = {
'total_matches': len(matches),
'total_offside_traps': 0,
'total_successful_traps': 0,
'total_one_on_one': 0,
'total_one_on_one_goals': 0,
'match_details': []
}
for match in matches:
match_stats = self.analyze_match(match)
all_stats['match_details'].append(match_stats)
# 累加总数
all_stats['total_offside_traps'] += match_stats['total_offside_traps']
all_stats['total_successful_traps'] += match_stats['successful_offside_traps']
all_stats['total_one_on_one'] += match_stats['one_on_one_chances']
all_stats['total_one_on_one_goals'] += match_stats['converted_goals']
return all_stats
def print_report(self, stats: Dict):
"""打印统计报告"""
print("=" * 60)
print("反越位成功形成单刀统计报告")
print("=" * 60)
print(f"分析比赛场次: {stats['total_matches']}")
print(f"总反越位尝试: {stats['total_offside_traps']}")
print(f"成功反越位: {stats['total_successful_traps']} "
f"(成功率: {stats['total_successful_traps']/stats['total_offside_traps']*100:.1f}%)")
print(f"反越位形成单刀: {stats['total_one_on_one']}")
print(f"单刀转化为进球: {stats['total_one_on_one_goals']} "
f"(转化率: {stats['total_one_on_one_goals']/stats['total_one_on_one']*100:.1f}%)")
print("\n详细事件日志:")
for log in self.events_log:
print(f" 第{log['time']}分钟 - {log['player']}({log['team']}) "
f"面对门将{log['opponent_goalkeeper']} "
f"{'⚽进球' if log['scored'] else '❌未进球'}")
print(f"\n反越位成功形成单刀次数: {stats['total_one_on_one']}")
# 使用示例
def main():
analyzer = FootballEventAnalyzer()
# 模拟比赛数据
matches_data = [
{
'id': 1,
'teams': ['利物浦', '曼联'],
'events': [
{'minute': 12, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '萨拉赫', 'team': '利物浦',
'scored': True, 'goalkeeper': '奥纳纳'},
{'minute': 35, 'type': 'offside_trap', 'result': 'failed',
'follow_up': None, 'player': '努涅斯', 'team': '利物浦'},
{'minute': 67, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '拉什福德', 'team': '曼联',
'scored': False, 'goalkeeper': '阿利松'},
]
},
{
'id': 2,
'teams': ['巴黎', '拜仁'],
'events': [
{'minute': 8, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '姆巴佩', 'team': '巴黎',
'scored': True, 'goalkeeper': '诺伊尔'},
{'minute': 45, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'one_on_one', 'player': '穆西亚拉', 'team': '拜仁',
'scored': False, 'goalkeeper': '多纳鲁马'},
{'minute': 78, 'type': 'offside_trap', 'result': 'successful',
'follow_up': 'corner', 'player': '内马尔', 'team': '巴黎'},
]
}
]
results = analyzer.analyze_multiple_matches(matches_data)
analyzer.print_report(results)
if __name__ == "__main__":
main()
使用Pandas进行数据分析和可视化
import pandas as pd
import matplotlib.pyplot as plt
# 创建数据框
data = {
'match_id': [1, 1, 1, 2, 2, 2],
'minute': [12, 35, 67, 8, 45, 78],
'player': ['萨拉赫', '努涅斯', '拉什福德', '姆巴佩', '穆西亚拉', '内马尔'],
'team': ['利物浦', '利物浦', '曼联', '巴黎', '拜仁', '巴黎'],
'offside_trap_result': ['successful', 'failed', 'successful', 'successful', 'successful', 'successful'],
'one_on_one': [True, False, True, True, True, False],
'scored': [True, False, False, True, False, False]
}
df = pd.DataFrame(data)
# 筛选反越位成功形成单刀的记录
one_on_one = df[(df['offside_trap_result'] == 'successful') & (df['one_on_one'] == True)]
print("=== 反越位成功形成单刀统计 ===")
print(f"总次数: {len(one_on_one)}")
# 按球队统计
team_stats = one_on_one.groupby('team').agg({
'one_on_one': 'count',
'scored': 'sum'
}).rename(columns={'one_on_one': '单刀次数', 'scored': '进球数'})
print("\n按球队统计:")
print(team_stats)
# 可视化
plt.figure(figsize=(10, 6))
team_stats.plot(kind='bar', y=['单刀次数', '进球数'])'反越位成功形成单刀统计')
plt.xlabel('球队')
plt.ylabel('次数')
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
这些案例可以帮助你统计反越位成功形成单刀的次数,并可以进行更深入的数据分析,根据你的具体需求,可以选择合适的方案。