本文目录导读:

我来为你设计一个足球比赛射门次数统计的Python案例,这个程序可以比较两支球队的射门情况。
基础版本:简单统计
def count_shots_basic():
"""简单统计两队射门次数"""
# 球队射门数据(模拟数据)
team_a_shots = [35, 42, 28, 51, 39, 47, 33, 55, 41, 38]
team_b_shots = [32, 45, 30, 48, 36, 44, 29, 50, 43, 40]
# 统计总射门次数
team_a_total = sum(team_a_shots)
team_b_total = sum(team_b_shots)
print("=" * 50)
print("球队A总射门次数:", team_a_total)
print("球队B总射门次数:", team_b_total)
print("=" * 50)
# 比较结果
if team_a_total > team_b_total:
print(f"🏆 球队A射门更多,多出 {team_a_total - team_b_total} 次")
elif team_b_total > team_a_total:
print(f"🏆 球队B射门更多,多出 {team_b_total - team_a_total} 次")
else:
print("🤝 两队射门次数相同!")
return team_a_total, team_b_total
进阶版本:详细统计
import random
from collections import Counter
class ShotAnalyzer:
"""足球射门分析器"""
def __init__(self, team_a_name="球队A", team_b_name="球队B"):
self.team_a_name = team_a_name
self.team_b_name = team_b_name
self.team_a_shots = []
self.team_b_shots = []
def generate_match_data(self, matches=10):
"""生成模拟比赛数据"""
for i in range(matches):
self.team_a_shots.append(random.randint(25, 60))
self.team_b_shots.append(random.randint(25, 60))
print(f"已生成 {matches} 场比赛数据")
def shot_statistics(self, shots):
"""计算统计数据"""
return {
'total': sum(shots),
'average': sum(shots) / len(shots),
'max': max(shots),
'min': min(shots),
'std_dev': (sum((x - sum(shots)/len(shots))**2 for x in shots) / len(shots)) ** 0.5
}
def analyze_comparison(self):
"""分析比较两队数据"""
stats_a = self.shot_statistics(self.team_a_shots)
stats_b = self.shot_statistics(self.team_b_shots)
print("\n" + "=" * 60)
print(f"{'指标':<10} {'球队A':<20} {'球队B':<20}")
print("=" * 60)
metrics = [
('总射门', 'total'),
('平均射门', 'average'),
('最高射门', 'max'),
('最低射门', 'min'),
('标准差', 'std_dev')
]
for metric_name, key in metrics:
print(f"{metric_name:<10} {stats_a[key]:<20.2f} {stats_b[key]:<20.2f}")
print("=" * 60)
# 胜负统计
a_win = sum(1 for i in range(len(self.team_a_shots))
if self.team_a_shots[i] > self.team_b_shots[i])
b_win = sum(1 for i in range(len(self.team_b_shots))
if self.team_b_shots[i] > self.team_a_shots[i])
draw = len(self.team_a_shots) - a_win - b_win
print(f"\n📊 射门次数对比:")
print(f"球队A射门多:{a_win} 场")
print(f"球队B射门多:{b_win} 场")
print(f"射门持平:{draw} 场")
# 最终判断
if stats_a['total'] > stats_b['total']:
print(f"\n🏆 {self.team_a_name}整体射门更多!")
elif stats_b['total'] > stats_a['total']:
print(f"\n🏆 {self.team_b_name}整体射门更多!")
else:
print("\n🤝 两队整体射门次数相同!")
def shot_frequency(self):
"""分析射门频率分布"""
all_shots = self.team_a_shots + self.team_b_shots
freq = Counter(all_shots)
print("\n📈 射门次数分布:")
print(f"{'射门次数':<10} {'出现次数':<10} {'柱状图'}")
for shots, count in sorted(freq.items()):
bar = '█' * count
print(f"{shots:<10} {count:<10} {bar}")
def visualize_comparison(self):
"""可视化比较"""
avg_a = sum(self.team_a_shots) / len(self.team_a_shots)
avg_b = sum(self.team_b_shots) / len(self.team_b_shots)
print("\n🎯 平均射门对比:")
print(f"{self.team_a_name}: {avg_a:.1f} |", "█" * int(avg_a))
print(f"{self.team_b_name}: {avg_b:.1f} |", "█" * int(avg_b))
def find_best_match(self):
"""找出射门最多的比赛"""
all_matches = []
for i, (a, b) in enumerate(zip(self.team_a_shots, self.team_b_shots)):
all_matches.append((i+1, a, b, a+b))
best_match = max(all_matches, key=lambda x: x[3])
print(f"\n⭐ 最佳比赛:第{best_match[0]}场")
print(f" 球队A射门:{best_match[1]}次")
print(f" 球队B射门:{best_match[2]}次")
print(f" 总射门:{best_match[3]}次")
# 主程序
def main():
"""主函数"""
print("⚽ 足球射门统计系统")
print("=" * 40)
# 创建分析器实例
analyzer = ShotAnalyzer("皇马", "巴萨")
# 生成模拟数据
analyzer.generate_match_data(10)
# 执行分析
analyzer.analyze_comparison()
analyzer.shot_frequency()
analyzer.visualize_comparison()
analyzer.find_best_match()
if __name__ == "__main__":
main()
可视化版本(使用matplotlib)
import matplotlib.pyplot as plt
import numpy as np
def visualize_match_shots():
"""使用matplotlib可视化两队射门数据"""
# 模拟数据
matches = list(range(1, 11))
team_a = [35, 42, 28, 51, 39, 47, 33, 55, 41, 38]
team_b = [32, 45, 30, 48, 36, 44, 29, 50, 43, 40]
# 创建图表
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 折线图
ax1.plot(matches, team_a, 'b-o', label='球队A')
ax1.plot(matches, team_b, 'r-o', label='球队B')
ax1.set_xlabel('比赛场次')
ax1.set_ylabel('射门次数')
ax1.set_title('两队射门次数对比')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 柱状图
x = np.arange(len(matches))
width = 0.35
bars1 = ax2.bar(x - width/2, team_a, width, label='球队A', color='#2E86AB')
bars2 = ax2.bar(x + width/2, team_b, width, label='球队B', color='#A23B72')
ax2.set_xlabel('比赛场次')
ax2.set_ylabel('射门次数')
ax2.set_title('射门次数柱状图')
ax2.set_xticks(x)
ax2.legend()
# 在柱状图上添加数值
for bars in [bars1, bars2]:
for bar in bars:
height = bar.get_height()
ax2.annotate(f'{height}',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3),
textcoords="offset points",
ha='center', va='bottom')
plt.tight_layout()
plt.show()
# 运行可视化
# visualize_match_shots()
使用示例和说明
# 1. 运行基础版本 count_shots_basic() # 2. 运行进阶版本 analyzer = ShotAnalyzer() analyzer.generate_match_data(10) analyzer.analyze_comparison()
运行结果示例:
⚽ 足球射门统计系统
========================================
已生成 10 场比赛数据
============================================================
指标 球队A 球队B
============================================================
总射门 398.00 405.00
平均射门 39.80 40.50
最高射门 56.00 55.00
最低射门 28.00 29.00
标准差 8.35 8.12
============================================================
📊 射门次数对比:
球队A射门多:4 场
球队B射门多:5 场
射门持平:1 场
🏆 球队B整体射门更多!
这个案例提供了:
- 基础统计:简单计算和比较
- 详细分析:包含平均、最大、最小等指标
- 可视化:图形化展示数据对比
- 统计分析:标准差、分布等
你可以根据自己的需求修改数据或添加更多功能。