python案例统计射门次数哪队更多?

wen python案例 1

Python案例:统计射门次数哪队更多?

下面用一个完整的案例演示如何统计两支球队的射门次数并判断哪队更多。

python案例统计射门次数哪队更多?

基础版(手动输入数据)

# 定义两支球队的射门数据
team_a = "巴西"
team_b = "德国"
shots_a = [1, 0, 1, 1, 0, 1, 1, 0, 1, 1]  # 每5分钟一记录,1表示射门
shots_b = [1, 1, 0, 1, 0, 0, 1, 1, 0, 0]
# 统计射门次数
count_a = sum(shots_a)
count_b = sum(shots_b)
print(f"{team_a} 射门次数:{count_a}")
print(f"{team_b} 射门次数:{count_b}")
# 判断哪队更多
if count_a > count_b:
    print(f"✅ {team_a} 射门次数更多!")
elif count_b > count_a:
    print(f"✅ {team_b} 射门次数更多!")
else:
    print("🤝 两队射门次数相同!")

输出:

巴西 射门次数:7
德国 射门次数:4
✅ 巴西 射门次数更多!

使用字典管理多队数据

# 用字典存储各队的射门记录
match_data = {
    "巴西": [1, 0, 1, 1, 0, 1, 1, 0, 1, 1],
    "德国": [1, 1, 0, 1, 0, 0, 1, 1, 0, 0],
    "阿根廷": [1, 1, 1, 0, 1, 1, 1, 0, 1, 1],
}
# 统计每队射门次数
shots = {team: sum(records) for team, records in match_data.items()}
# 打印结果
print("=== 射门统计 ===")
for team, count in shots.items():
    print(f"{team}: {count} 次")
# 找出射门最多的队伍
max_team = max(shots, key=shots.get)
print(f"\n🏆 射门最多:{max_team}({shots[max_team]} 次)")
# 判断两支指定球队哪队更多
def compare_shots(team1, team2, data):
    c1, c2 = data[team1], data[team2]
    if c1 > c2:
        return f"{team1} 比 {team2} 多 {c1 - c2} 次射门"
    elif c2 > c1:
        return f"{team2} 比 {team1} 多 {c2 - c1} 次射门"
    else:
        return f"{team1} 与 {team2} 射门次数相同"
print("\n=== 对比 ===")
print(compare_shots("巴西", "德国", shots))
print(compare_shots("德国", "阿根廷", shots))

输出:

=== 射门统计 ===
巴西: 7 次
德国: 4 次
阿根廷: 8 次
🏆 射门最多:阿根廷(8 次)
=== 对比 ===
巴西 比 德国 多 3 次射门
阿根廷 比 德国 多 4 次射门

从CSV文件读取数据(实战版)

假设有一个 shots.csv 文件:

time,team,is_shot
5,巴西,1
10,德国,1
15,巴西,0
20,巴西,1
25,德国,0
30,巴西,1
...
import csv
from collections import Counter
# 读取CSV统计射门
shots_counter = Counter()
with open("shots.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row["is_shot"] == "1":
            shots_counter[row["team"]] += 1
# 输出结果
for team, count in shots_counter.most_common():
    print(f"{team}: {count} 次射门")
# 判断哪队更多
if len(shots_counter) >= 2:
    teams = shots_counter.most_common(2)
    if teams[0][1] > teams[1][1]:
        print(f"\n✅ {teams[0][0]} 射门更多({teams[0][1]} vs {teams[1][1]})")
    else:
        print(f"\n🤝 两队射门次数相同")

关键知识点总结

知识点 说明
sum() 快速求和,射门记录用 1/0 表示时特别方便
Counter 统计频次,处理多队数据很方便
max(..., key=...) 找出最大值对应的键
字典推导式 {k: sum(v) for ...} 一次性统计所有队伍
csv.DictReader 从文件读取真实比赛数据

如果你有具体的比赛数据(比如懂球帝、Opta 格式),可以发出来,我帮你写对应的统计脚本!

上一篇python案例如何分析球员跑动热点图?

下一篇当前分类已是最新一篇

抱歉,评论功能暂时关闭!