本文目录导读:

我来提供一个统计球员评分最高者的Python案例,包含完整代码和说明。
案例:统计球员评分最高者
使用字典和max函数
# 球员数据:{球员名: 评分}
players = {
"梅西": 9.5,
"C罗": 8.9,
"姆巴佩": 9.2,
"哈兰德": 9.3,
"内马尔": 8.7,
"德布劳内": 9.1
}
# 方法1:使用 max() 配合 key 参数
best_player = max(players, key=players.get)
best_score = players[best_player]
print(f"最高分球员:{best_player},评分:{best_score}")
# 输出:最高分球员:梅西,评分:9.5
处理并列最高分的情况
players = {
"梅西": 9.5,
"C罗": 9.5, # 与梅西并列
"姆巴佩": 9.2,
"哈兰德": 9.3,
"内马尔": 8.7
}
# 先找出最高分
max_score = max(players.values())
# 再找出所有达到最高分的球员
best_players = [name for name, score in players.items() if score == max_score]
print(f"最高评分:{max_score}")
print(f"获得最高分的球员:{', '.join(best_players)}")
# 输出:
# 最高评分:9.5
# 获得最高分的球员:梅西, C罗
完整的实战案例(含数据读取)
import csv
from collections import defaultdict
# 假设有一个球员评分CSV文件 player_ratings.csv
# 格式:姓名,球队,评分
def find_top_rated_player(csv_file):
"""统计评分最高的球员"""
players_data = []
# 读取数据(这里用示例数据模拟)
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
players_data.append({
'name': row['name'],
'team': row['team'],
'rating': float(row['rating'])
})
if not players_data:
return None
# 找最高分
max_rating = max(p['rating'] for p in players_data)
# 找所有最高分球员
top_players = [p for p in players_data if p['rating'] == max_rating]
return top_players, max_rating
# 模拟数据测试
sample_data = [
{'name': '梅西', 'team': '迈阿密国际', 'rating': 9.5},
{'name': 'C罗', 'team': '利雅得胜利', 'rating': 8.9},
{'name': '姆巴佩', 'team': '皇马', 'rating': 9.2},
{'name': '哈兰德', 'team': '曼城', 'rating': 9.3},
{'name': '德布劳内', 'team': '曼城', 'rating': 9.5} # 并列最高
]
max_rating = max(p['rating'] for p in sample_data)
top_players = [p for p in sample_data if p['rating'] == max_rating]
print(f"最高评分:{max_rating}\n")
print("最高分球员名单:")
for p in top_players:
print(f" ⭐ {p['name']} ({p['team']}) - {p['rating']}分")
使用pandas(适合大量数据)
import pandas as pd
# 构建数据
df = pd.DataFrame({
'球员': ['梅西', 'C罗', '姆巴佩', '哈兰德', '德布劳内'],
'评分': [9.5, 8.9, 9.2, 9.3, 9.5]
})
# 找最高分
max_score = df['评分'].max()
top_players = df[df['评分'] == max_score]
print(f"最高分:{max_score}")
print("最高分球员:")
print(top_players.to_string(index=False))
核心知识点
| 方法 | 关键函数 | 适用场景 |
|---|---|---|
| 字典 | max(dict, key=dict.get) |
简单数据,唯一最高分 |
| 列表推导 | max() + 推导式 |
处理并列情况 |
| pandas | df[df['col']==max] |
大量数据、表格形式 |
| csv模块 | csv.DictReader |
从文件读取 |
要点总结:
max(players, key=players.get)返回的是键(球员名),不是值- 处理并列最高分时,需先求最大值,再用列表推导筛选
- 实际项目推荐用
pandas,代码简洁且性能好
如果你有具体的球员数据格式(Excel/CSV/列表),我可以帮你写针对性的代码。
版权声明:本站文章为原创整理,转载请注明出处。