python案例统计球员评分最高者是谁?

wen python案例 3

Python案例:统计球员评分最高者

下面通过一个完整案例,演示如何用Python统计球员评分最高者,包含两种常见场景:单个最高分球员 和 处理并列最高分。

python案例统计球员评分最高者是谁?

场景1:找出评分最高的球员

# 球员数据:姓名 -> 评分
players = {
    "梅西": 9.2,
    "姆巴佩": 8.7,
    "哈兰德": 9.0,
    "贝林厄姆": 8.9,
    "维尼修斯": 9.2,
    "凯恩": 8.5
}
# 方法1:使用 max() + key 参数
best_player = max(players, key=players.get)
print(f"评分最高的球员是:{best_player},评分:{players[best_player]}")
# 输出:评分最高的球员是:梅西,评分:9.2

场景2:处理并列最高分(推荐)

实际比赛中经常出现并列,上面方法只能返回一个,下面用列表推导式找出所有最高分球员:

players = {
    "梅西": 9.2,
    "姆巴佩": 8.7,
    "哈兰德": 9.0,
    "贝林厄姆": 8.9,
    "维尼修斯": 9.2,
    "凯恩": 8.5
}
# 第一步:找到最高评分
max_score = max(players.values())
# 第二步:筛选出所有达到最高分的球员
top_players = [name for name, score in players.items() if score == max_score]
print(f"最高评分:{max_score}")
print(f"获得最高分的球员:{', '.join(top_players)}")
# 输出:
# 最高评分:9.2
# 获得最高分的球员:梅西, 维尼修斯

场景3:球员数据以列表形式存储(更贴近实际)

如果数据来自表格或数据库,通常是列表套字典的格式:

players = [
    {"name": "梅西", "team": "迈阿密国际", "score": 9.2},
    {"name": "姆巴佩", "team": "皇马", "score": 8.7},
    {"name": "哈兰德", "team": "曼城", "score": 9.0},
    {"name": "贝林厄姆", "team": "皇马", "score": 8.9},
    {"name": "维尼修斯", "team": "皇马", "score": 9.2},
]
# 找最高分
max_score = max(p["score"] for p in players)
# 找所有最高分球员
top_players = [p for p in players if p["score"] == max_score]
print(f"最高评分:{max_score}")
for p in top_players:
    print(f"  {p['name']} - {p['team']}")

输出:

最高评分:9.2
  梅西 - 迈阿密国际
  维尼修斯 - 皇马

场景4:使用 pandas(适合大数据量)

import pandas as pd
df = pd.DataFrame({
    "球员": ["梅西", "姆巴佩", "哈兰德", "贝林厄姆", "维尼修斯"],
    "球队": ["迈阿密国际", "皇马", "曼城", "皇马", "皇马"],
    "评分": [9.2, 8.7, 9.0, 8.9, 9.2]
})
# 方法1:取评分最高的行(并列时只取第一条)
top1 = df.loc[df["评分"].idxmax()]
print(top1)
# 方法2:找出所有并列最高分
max_score = df["评分"].max()
top_all = df[df["评分"] == max_score]
print(top_all)

核心知识点总结

需求 方法
找最大值对应的键 max(dict, key=dict.get)
找所有并列最大 先 max() 再列表推导式筛选
列表套字典求最大 max(players, key=lambda x: x["score"])
pandas 求最大行 df.loc[df["评分"].idxmax()]

小提示:max() 的 key 参数

# 字典
max(players, key=players.get)          # 返回键(球员名)
# 列表套字典
max(players, key=lambda x: x["score"]) # 返回整个字典
# 使用 operator.itemgetter(更快)
from operator import itemgetter
max(players, key=itemgetter("score"))

需要我扩展成读取CSV/Excel文件或按球队分组统计最高分的版本吗?

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