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

wen python案例 1

本文目录导读:

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

  1. 方案一:字典存储(最常用)
  2. 方案二:列表+元组(适合数据较多)
  3. 方案三:类封装(面向对象)
  4. 方案四:交互式输入版
  5. 方案五:带异常处理和数据校验
  6. 运行结果示例
  7. 核心知识点总结

字典存储(最常用)

def find_highest_scorer_dict():
    """使用字典存储球员评分"""
    # 球员评分数据
    player_scores = {
        '勒布朗·詹姆斯': 32.5,
        '凯文·杜兰特': 28.7,
        '斯蒂芬·库里': 30.1,
        '扬尼斯·阿德托昆博': 31.2,
        '卢卡·东契奇': 33.9
    }
    # 方法1:使用max函数
    highest_player = max(player_scores, key=player_scores.get)
    highest_score = player_scores[highest_player]
    print("="*50)
    print("球员评分统计结果")
    print("="*50)
    print(f"评分最高的球员: {highest_player}")
    print(f"最高评分: {highest_score}")
    # 显示所有球员评分排名
    print("\n球员评分排名:")
    sorted_players = sorted(player_scores.items(), key=lambda x: x[1], reverse=True)
    for i, (player, score) in enumerate(sorted_players, 1):
        medal = {1: "🥇", 2: "🥈", 3: "🥉"}.get(i, f"{i}.")
        print(f"{medal} {player}: {score}分")
    return highest_player, highest_score
find_highest_scorer_dict()

列表+元组(适合数据较多)

def find_highest_scorer_list():
    """使用列表存储球员评分"""
    # 使用元组列表 (球员名, 评分)
    players = [
        ('梅西', 8.9),
        ('C罗', 8.7),
        ('内马尔', 8.5),
        ('姆巴佩', 9.1),
        ('哈兰德', 8.8),
        ('贝林厄姆', 9.0)
    ]
    # 找出最高分球员
    highest_player = max(players, key=lambda x: x[1])
    print("="*50)
    print("足球球员评分统计")
    print("="*50)
    print(f"评分最高的球员: {highest_player[0]}")
    print(f"最高评分: {highest_player[1]}")
    # 按评分降序排列
    sorted_players = sorted(players, key=lambda x: x[1], reverse=True)
    print("\n完整排行榜:")
    for i, (name, score) in enumerate(sorted_players, 1):
        print(f"{i:2d}. {name:10s} 评分: {score:.1f}")
    return highest_player
find_highest_scorer_list()

类封装(面向对象)

class PlayerStats:
    """球员统计类"""
    def __init__(self):
        self.players = {}
        self.scores = []
    def add_player(self, name, score):
        """添加球员及评分"""
        self.players[name] = score
        self.scores.append((name, score))
    def get_highest_scorer(self):
        """获取最高分球员"""
        if not self.players:
            return None, None
        highest_name = max(self.players, key=self.players.get)
        highest_score = self.players[highest_name]
        return highest_name, highest_score
    def get_top_n(self, n=3):
        """获取前N名球员"""
        sorted_scores = sorted(self.scores, key=lambda x: x[1], reverse=True)
        return sorted_scores[:n]
    def display_stats(self):
        """显示完整统计"""
        print("\n" + "="*50)
        print("球员评分统计报告")
        print("="*50)
        if not self.players:
            print("暂无球员数据")
            return
        # 显示最高分
        name, score = self.get_highest_scorer()
        print(f"🏆 最高分球员: {name} ({score}分)")
        # 显示排名
        print("\n完整排行榜:")
        sorted_scores = sorted(self.scores, key=lambda x: x[1], reverse=True)
        for i, (player, score) in enumerate(sorted_scores, 1):
            medal = {1: "🥇", 2: "🥈", 3: "🥉"}.get(i, f"{i}.")
            print(f"{medal} {player:15s} 评分: {score:.1f}")
        # 显示统计数据
        avg_score = sum(self.players.values()) / len(self.players)
        print(f"\n📊 平均评分: {avg_score:.2f}")
        print(f"📈 最高评分: {max(self.players.values()):.1f}")
        print(f"📉 最低评分: {min(self.players.values()):.1f}")
def class_demo():
    """类封装示例"""
    stats = PlayerStats()
    # 添加球员数据
    stats.add_player('李宁', 9.2)
    stats.add_player('姚明', 9.8)
    stats.add_player('易建联', 8.5)
    stats.add_player('周琦', 7.8)
    stats.add_player('王治郅', 9.5)
    # 显示统计结果
    stats.display_stats()
    # 获取前三名
    top3 = stats.get_top_n(3)
    print("\n🏆 前三名:")
    for rank, (name, score) in enumerate(top3, 1):
        print(f"  第{rank}名: {name} - {score}分")
class_demo()

交互式输入版

def interactive_input():
    """交互式输入球员评分"""
    print("="*50)
    print("球员评分统计系统")
    print("="*50)
    players = {}
    n = int(input("请输入球员人数: "))
    # 输入球员信息
    for i in range(n):
        print(f"\n请输入第{i+1}名球员信息:")
        name = input("  球员姓名: ").strip()
        while True:
            try:
                score = float(input("  评分(0-10): "))
                if 0 <= score <= 10:
                    break
                else:
                    print("  评分必须在0-10之间!")
            except ValueError:
                print("  请输入数字!")
        players[name] = score
    # 统计结果
    highest = max(players, key=players.get)
    print("\n" + "="*50)
    print("📊 统计结果")
    print("="*50)
    print(f"🏆 评分最高的球员: {highest}")
    print(f"💯 最高评分: {players[highest]}")
    # 显示所有球员
    print("\n📋 所有球员评分:")
    for name, score in sorted(players.items(), key=lambda x: x[1], reverse=True):
        bar = "█" * int(score * 10)  # 可视化条形图
        print(f"{name:8s} | {score:5.1f} | {bar}")
# 运行交互式程序
interactive_input()

带异常处理和数据校验

def robust_statistics():
    """健壮的统计函数,包含异常处理"""
    sample_data = [
        ('库里', 92.5),
        ('杜兰特', 88.3),
        ('詹姆斯', 91.2),
        ('字母哥', 87.8),
        ('东契奇', 94.1)
    ]
    try:
        if not sample_data:
            raise ValueError("数据列表为空")
        # 检查数据结构
        for item in sample_data:
            if not isinstance(item, tuple) or len(item) != 2:
                raise TypeError("数据格式错误")
            if not isinstance(item[1], (int, float)):
                raise TypeError("评分必须是数字")
        # 计算统计
        highest = max(sample_data, key=lambda x: x[1])
        all_scores = [score for _, score in sample_data]
        # 输出结果
        print("\n" + "="*60)
        print("🏀 NBA球员评分分析")
        print("="*60)
        print(f"球员总数: {len(sample_data)}")
        print(f"评分最高: {highest[0]} ({highest[1]}分)")
        print(f"平均评分: {sum(all_scores)/len(all_scores):.2f}")
        print(f"评分中位数: {sorted(all_scores)[len(all_scores)//2]:.1f}")
        # 找并列最高分
        max_score = max(all_scores)
        tie_players = [name for name, score in sample_data if score == max_score]
        if len(tie_players) > 1:
            print(f"⚠️ 并列最高分球员: {', '.join(tie_players)}")
    except ValueError as e:
        print(f"数据错误: {e}")
    except TypeError as e:
        print(f"类型错误: {e}")
    except Exception as e:
        print(f"未知错误: {e}")
robust_statistics()

运行结果示例

==================================================
球员评分统计结果
==================================================
评分最高的球员: 卢卡·东契奇
最高评分: 33.9
球员评分排名:
🥇 卢卡·东契奇: 33.9分
🥈 勒布朗·詹姆斯: 32.5分
🥉 扬尼斯·阿德托昆博: 31.2分
4. 斯蒂芬·库里: 30.1分
5. 凯文·杜兰特: 28.7分

核心知识点总结

  1. max()函数:使用key参数指定比较依据
  2. lambda表达式:简化匿名函数定义
  3. 字典操作dict.get(key)获取值,dict.items()遍历键值对
  4. 排序sorted()函数配合keyreverse参数
  5. 类封装:面向对象编程思想
  6. 异常处理:try-except捕获错误

这些方法可以根据实际需求灵活选择,基础版推荐使用字典+max()的方式,数据量大时考虑性能优化。

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