本文目录导读:

我来帮你写一个统计足球比赛射门次数的脚本,这里提供几种方案:
简单手动输入统计
def count_shots():
"""手动输入两队射门次数并比较"""
print("=== 足球射门统计 ===")
team_a = input("请输入A队名称: ")
team_b = input("请输入B队名称: ")
shots_a = int(input(f"请输入{team_a}的射门次数: "))
shots_b = int(input(f"请输入{team_b}的射门次数: "))
total = shots_a + shots_b
print(f"\n总射门次数: {total}")
print(f"{team_a}: {shots_a} 次 ({shots_a/total*100:.1f}%)")
print(f"{team_b}: {shots_b} 次 ({shots_b/total*100:.1f}%)")
if shots_a > shots_b:
print(f"\n🏆 {team_a} 射门更多!多出 {shots_a - shots_b} 次")
elif shots_b > shots_a:
print(f"\n🏆 {team_b} 射门更多!多出 {shots_b - shots_a} 次")
else:
print(f"\n⚖️ 两队射门次数相同!")
if __name__ == "__main__":
count_shots()
从CSV文件批量统计
假设有一个 shots.csv 文件:
team,player,shots 阿根廷,梅西,5 阿根廷,劳塔罗,3 法国,姆巴佩,6 法国,格列兹曼,2 阿根廷,迪马利亚,1
脚本:
import csv
from collections import defaultdict
def analyze_shots_from_csv(filename="shots.csv"):
"""从CSV文件统计各队射门次数"""
team_shots = defaultdict(int)
player_shots = defaultdict(int)
try:
with open(filename, encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
team = row["team"]
player = row["player"]
shots = int(row["shots"])
team_shots[team] += shots
player_shots[f"{team}-{player}"] += shots
except FileNotFoundError:
print(f"找不到文件 {filename}")
return
# 按射门次数排序
sorted_teams = sorted(team_shots.items(), key=lambda x: x[1], reverse=True)
print("=== 各队射门统计 ===")
for i, (team, shots) in enumerate(sorted_teams, 1):
print(f"{i}. {team}: {shots} 次")
if len(sorted_teams) >= 2:
winner, winner_shots = sorted_teams[0]
runner, runner_shots = sorted_teams[1]
if winner_shots > runner_shots:
print(f"\n🏆 {winner} 射门最多,比 {runner} 多 {winner_shots - runner_shots} 次")
else:
print(f"\n⚖️ {winner} 和 {runner} 射门次数相同")
if __name__ == "__main__":
analyze_shots_from_csv()
用 pandas 处理(适合大数据)
import pandas as pd
def analyze_shots_pandas(filename="shots.csv"):
"""用pandas统计射门次数"""
df = pd.read_csv(filename)
team_stats = df.groupby("team")["shots"].agg(["sum", "mean", "count"])
team_stats.columns = ["总射门", "场均射门", "球员数"]
team_stats = team_stats.sort_values("总射门", ascending=False)
print("=== 各队射门统计 ===")
print(team_stats)
if len(team_stats) >= 2:
top_team = team_stats.index[0]
print(f"\n🏆 射门最多的球队: {top_team} ({team_stats.iloc[0]['总射门']} 次)")
if __name__ == "__main__":
analyze_shots_pandas()
使用说明
- 方案一:直接运行,手动输入数据,适合临时快速对比
- 方案二:需要准备
shots.csv文件,标准库即可,无需额外安装 - 方案三:需要
pip install pandas,功能最强大
你现在的场景是哪种?
- 如果是手头有一场比赛数据想快速对比 → 用方案一
- 如果是整届赛事/多场比赛数据 → 用方案二或三
- 如果数据来自 API(如 FotMob、API-Football)→ 告诉我,我可以改成自动抓取版本