本文目录导读:

我来提供一个实用的脚本来统计球员评分最高者,这里给出Python和JavaScript两个版本:
Python版本
import csv
from typing import List, Dict
def find_highest_rated_player(csv_file: str) -> Dict:
"""
从CSV文件中找出评分最高的球员
CSV格式: name,position,rating
"""
players = []
try:
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
players.append({
'name': row['name'],
'position': row.get('position', 'N/A'),
'rating': float(row['rating'])
})
except FileNotFoundError:
print(f"文件 {csv_file} 不存在")
return None
if not players:
print("没有球员数据")
return None
# 找出最高评分
top_player = max(players, key=lambda p: p['rating'])
# 找出所有并列最高分
highest_rating = top_player['rating']
tied_players = [p for p in players if p['rating'] == highest_rating]
print(f"最高评分: {highest_rating}")
print(f"最高分球员 ({len(tied_players)}人):")
for p in tied_players:
print(f" - {p['name']} ({p['position']}) - {p['rating']}")
# 显示Top 5排名
sorted_players = sorted(players, key=lambda p: p['rating'], reverse=True)
print("\nTop 5 排名:")
for i, p in enumerate(sorted_players[:5], 1):
print(f" {i}. {p['name']} - {p['rating']}")
return top_player
def analyze_from_dict(players: List[Dict]) -> Dict:
"""
直接从字典列表分析(适用于API数据、数据库查询结果等)
"""
if not players:
return None
# 兼容不同字段名
def get_rating(p):
return p.get('rating') or p.get('score') or p.get('评分', 0)
def get_name(p):
return p.get('name') or p.get('player_name') or p.get('球员', 'Unknown')
top = max(players, key=lambda p: float(get_rating(p)))
print(f"最高分球员: {get_name(top)} - 评分: {get_rating(top)}")
return top
if __name__ == '__main__':
# 方式1: 从CSV读取
# find_highest_rated_player('players.csv')
# 方式2: 直接使用数据
sample_players = [
{'name': '梅西', 'position': 'FW', 'rating': 9.5},
{'name': '姆巴佩', 'position': 'FW', 'rating': 9.2},
{'name': '德布劳内', 'position': 'MF', 'rating': 9.7},
{'name': '哈兰德', 'position': 'FW', 'rating': 9.7},
{'name': '范戴克', 'position': 'DF', 'rating': 8.8},
]
analyze_from_dict(sample_players)
JavaScript/Node.js 版本
const fs = require('fs');
/**
* 从JSON文件或数组统计最高评分球员
*/
function findHighestRated(players) {
if (!players || players.length === 0) {
console.log('没有球员数据');
return null;
}
// 找出最高分
const maxRating = Math.max(...players.map(p => parseFloat(p.rating)));
const topPlayers = players.filter(p => parseFloat(p.rating) === maxRating);
console.log(`最高评分: ${maxRating}`);
console.log(`最高分球员 (${topPlayers.length}人):`);
topPlayers.forEach(p => {
console.log(` - ${p.name} (${p.position || 'N/A'}) - ${p.rating}`);
});
// Top 5 排名
const sorted = [...players].sort((a, b) => b.rating - a.rating);
console.log('\nTop 5 排名:');
sorted.slice(0, 5).forEach((p, i) => {
console.log(` ${i + 1}. ${p.name} - ${p.rating}`);
});
return topPlayers[0];
}
// 从CSV文件读取
function analyzeCSV(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.trim().split('\n');
const headers = lines[0].split(',').map(h => h.trim());
const players = lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim());
return {
name: values[headers.indexOf('name')],
position: values[headers.indexOf('position')],
rating: parseFloat(values[headers.indexOf('rating')])
};
});
return findHighestRated(players);
}
// 示例
const players = [
{ name: '梅西', position: 'FW', rating: 9.5 },
{ name: '姆巴佩', position: 'FW', rating: 9.2 },
{ name: '德布劳内', position: 'MF', rating: 9.7 },
{ name: '哈兰德', position: 'FW', rating: 9.7 },
];
findHighestRated(players);
// analyzeCSV('players.csv');
示例CSV文件 (players.csv)
name,position,rating 梅西,FW,9.5 姆巴佩,FW,9.2 德布劳内,MF,9.7 哈兰德,FW,9.7 范戴克,DF,8.8
输出示例
最高评分: 9.7
最高分球员 (2人):
- 德布劳内 (MF) - 9.7
- 哈兰德 (FW) - 9.7
Top 5 排名:
1. 德布劳内 - 9.7
2. 哈兰德 - 9.7
3. 梅西 - 9.5
4. 姆巴佩 - 9.2
5. 范戴克 - 8.8
关键特性说明
| 特性 | 说明 |
|---|---|
| 并列处理 | 自动识别所有达到最高分的球员 |
| 字段兼容 | 支持 rating/score/评分 多种字段名 |
| 数据类型 | 使用 float 转换确保数值比较正确 |
| 空值保护 | 处理空数据和文件不存在情况 |
| 扩展排名 | 附带 Top N 排名输出 |
使用建议
- 足球/篮球等运动数据:按位置过滤(如只看前锋)
- 多维度统计:可扩展为加权评分(进球+助攻+传球成功率)
- 实时数据:从API获取后直接调用
analyze_from_dict
如果你有具体的数据结构(如JSON格式、数据库表结构)或评分字段(如WhoScored、SofaScore等),告诉我我可以进一步适配。