综合python案例,谁更有机会晋级?

wen python案例 1

我来设计一个综合Python案例,模拟一个真实的"员工晋级评估系统"。

综合python案例,谁更有机会晋级?

案例场景:公司员工晋级评估系统

需求说明

公司需要从5名员工中选出晋级者,评估标准包括:

  • 工作绩效(KPI)
  • 技能水平
  • 团队协作
  • 项目贡献
  • 领导潜力

完整实现代码

import json
import random
from datetime import datetime
from typing import List, Dict
import pandas as pd
import numpy as np
class Employee:
    """员工类"""
    def __init__(self, name, dept, position, years):
        self.name = name
        self.dept = dept
        self.position = position
        self.years = years
        self.scores = {}  # 各维度评分
        self.total_score = 0
        self.ranking = 0
    def set_scores(self, kpi, skill, teamwork, project, leadership):
        """设置各维度评分"""
        self.scores = {
            'KPI': kpi,
            '技能水平': skill,
            '团队协作': teamwork,
            '项目贡献': project,
            '领导潜力': leadership
        }
        # 加权计算总分
        weights = {'KPI': 0.3, '技能水平': 0.2, '团队协作': 0.2, 
                  '项目贡献': 0.2, '领导潜力': 0.1}
        self.total_score = sum(self.scores[k] * weights[k] 
                              for k in self.scores.keys())
class PromotionSystem:
    """晋级评估系统"""
    def __init__(self):
        self.employees = []
        self.history = []  # 历史评估记录
    def add_employee(self, emp: Employee):
        """添加员工"""
        self.employees.append(emp)
    def generate_scores(self):
        """生成评分数据(模拟真实评估)"""
        # 各维度基准分数(不同部门水平不同)
        dept_baseline = {
            '技术部': {'KPI': 85, '技能水平': 88},
            '市场部': {'KPI': 90, '技能水平': 82},
            '运营部': {'KPI': 88, '技能水平': 80},
            '人事部': {'KPI': 82, '技能水平': 85}
        }
        for emp in self.employees:
            base = dept_baseline.get(emp.dept, {'KPI': 85, '技能水平': 85})
            # 模拟工作年限加分
            exp_bonus = min(emp.years * 1.5, 10)
            kpi = min(base['KPI'] + random.uniform(-8, 8) + exp_bonus * 0.3, 100)
            skill = min(base['技能水平'] + random.uniform(-10, 10), 100)
            teamwork = random.uniform(75, 98)
            project = random.uniform(70, 100)
            leadership = random.uniform(65, 95) + random.uniform(-5, 10)
            emp.set_scores(kpi, skill, teamwork, project, leadership)
    def evaluate(self):
        """执行评估"""
        # 生成评分
        self.generate_scores()
        # 按总分排序
        self.employees.sort(key=lambda x: x.total_score, reverse=True)
        # 设置排名
        for i, emp in enumerate(self.employees, 1):
            emp.ranking = i
        # 晋级规则处理
        result = self.apply_promotion_rules()
        # 记录历史
        self.save_history()
        return result
    def apply_promotion_rules(self):
        """应用晋级规则"""
        rules_checked = []
        promoted = []
        for emp in self.employees:
            checks = {
                'name': emp.name,
                'dept': emp.dept,
                'total_score': round(emp.total_score, 2),
                'ranking': emp.ranking,
                # 规则1: 总分达到晋级线 (>=85)
                'rule_score_pass': emp.total_score >= 85,
                # 规则2: 工作年限 >= 2年
                'rule_years_pass': emp.years >= 2,
                # 规则3: 无单项低于70分
                'rule_min_score_pass': all(v >= 70 for v in emp.scores.values()),
                # 规则4: 领导力 >= 75(管理岗位)
                'rule_leadership_pass': emp.scores['领导潜力'] >= 75
            }
            # 综合判断是否晋级
            checks['qualified'] = (checks['rule_score_pass'] and 
                                  checks['rule_years_pass'] and 
                                  checks['rule_min_score_pass'] and
                                  checks['rule_leadership_pass'])
            if checks['qualified']:
                promoted.append(emp)
            rules_checked.append(checks)
        return {'promoted': promoted, 'details': rules_checked}
    def save_history(self):
        """保存评估记录到文件"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"evaluation_{timestamp}.json"
        data = []
        for emp in self.employees:
            data.append({
                'name': emp.name,
                'dept': emp.dept,
                'ranking': emp.ranking,
                'total_score': emp.total_score,
                'scores': emp.scores
            })
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        return filename
class DataAnalyzer:
    """数据分析器"""
    @staticmethod
    def analyze_results(results: Dict):
        """分析评估结果"""
        print("=" * 50)
        print("🎯 晋级评估结果")
        print("=" * 50)
        promoted_names = [emp.name for emp in results['promoted']]
        for detail in results['details']:
            status = "✅ 晋级" if detail['qualified'] else "❌ 未晋级"
            print(f"\n{detail['name']} ({detail['dept']}) - 第{detail['ranking']}名")
            print(f"总分: {detail['total_score']}")
            print(f"状态: {status}")
            print("规则检查:")
            print(f"  - 总分达标: {'✓' if detail['rule_score_pass'] else '✗'}")
            print(f"  - 工作年限: {'✓' if detail['rule_years_pass'] else '✗'}")
            print(f"  - 单项最低: {'✓' if detail['rule_min_score_pass'] else '✗'}")
            print(f"  - 领导潜力: {'✓' if detail['rule_leadership_pass'] else '✗'}")
        # 统计分析
        print("\n" + "=" * 50)
        print("📊 统计分析")
        print("=" * 50)
        scores = [d['total_score'] for d in results['details']]
        avg_score = np.mean(scores)
        med_score = np.median(scores)
        std_score = np.std(scores)
        print(f"平均分: {avg_score:.2f}")
        print(f"中位数: {med_score:.2f}")
        print(f"标准差: {std_score:.2f}")
        print(f"最高分: {max(scores):.2f}")
        print(f"最低分: {min(scores):.2f}")
        # 部门分布
        dept_promoted = {}
        for emp in results['promoted']:
            dept_promoted[emp.dept] = dept_promoted.get(emp.dept, 0) + 1
        print(f"\n晋级名单:")
        for name in promoted_names:
            print(f"  ⭐ {name}")
    @staticmethod
    def save_excel_report(results: Dict, filename="promotion_report.xlsx"):
        """导出Excel报告"""
        rows = []
        for detail in results['details']:
            rows.append({
                '姓名': detail['name'],
                '部门': detail['dept'],
                '排名': detail['ranking'],
                '总分': detail['total_score'],
                '是否晋级': '是' if detail['qualified'] else '否'
            })
        df = pd.DataFrame(rows)
        df.to_excel(filename, index=False)
        print(f"\n📁 Excel报告已保存: {filename}")
        # 生成图表数据
        import matplotlib.pyplot as plt
        plt.figure(figsize=(10, 6))
        scores = [row['总分'] for row in rows]
        names = [row['姓名'] for row in rows]
        colors = plt.cm.viridis(np.linspace(0.2, 0.9, len(names)))
        plt.bar(names, scores, color=colors)
        plt.title('员工晋级评估分数')
        plt.ylabel('总分')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('scores_bar_chart.png')
        print("📊 图表已保存: scores_bar_chart.png")
class AdvancedFeatures:
    """高级功能演示"""
    @staticmethod
    def monte_carlo_simulation(system, iterations=1000):
        """蒙特卡洛模拟 - 评估晋级概率"""
        promotion_count = {}
        for _ in range(iterations):
            # 重置员工数据
            for emp in system.employees:
                pass
            # 模拟评估
            result = system.evaluate()
            for emp in result['promoted']:
                promotion_count[emp.name] = promotion_count.get(emp.name, 0) + 1
        # 计算概率
        probabilities = {name: (count/iterations*100) for name, count in promotion_count.items()}
        print("\n" + "=" * 50)
        print("🎲 蒙特卡洛模拟结果 (1000次)")
        print("=" * 50)
        sorted_prob = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
        for name, prob in sorted_prob:
            print(f"{name}: {prob:.1f}%")
        return probabilities
def main():
    """主函数"""
    print("🚀 员工晋级评估系统启动")
    print("-" * 30)
    # 创建系统
    system = PromotionSystem()
    # 添加员工
    employees_data = [
        Employee("张伟", "技术部", "高级工程师", 5),
        Employee("李娜", "市场部", "市场经理", 3),
        Employee("王强", "技术部", "工程师", 2),
        Employee("刘洋", "运营部", "运营专员", 1),
        Employee("陈晨", "人事部", "HR主管", 4)
    ]
    for emp in employees_data:
        system.add_employee(emp)
    # 执行评估
    results = system.evaluate()
    # 分析结果
    analyzer = DataAnalyzer()
    analyzer.analyze_results(results)
    # 导出报告
    analyzer.save_excel_report(results)
    # 高级分析
    advanced = AdvancedFeatures()
    # 由于蒙特卡洛模拟会重置数据,单独运行
    # advanced.monte_carlo_simulation(system)
    print("\n" + "=" * 50)
    print("💡 评估总结")
    print("=" * 50)
    # 找出晋级者和未晋级者
    qualified = [emp for emp in system.employees if emp.ranking <= 3]
    print(f"\n晋级名额: 3人")
    print(f"本次晋级候选人:")
    for emp in system.employees[:3]:
        print(f"  {emp.ranking}. {emp.name} - 总分: {emp.total_score:.2f}")
    # 预测和洞察
    print("\n📌 分析建议:")
    print("1. 如果考量部门平衡,可以调整晋级名额")
    print("2. 技术部员工在技能方面表现突出")
    print("3. 建议对低分维度进行针对性培训")
if __name__ == "__main__":
    main()

额外功能:数据可视化

# 可添加到系统中的可视化模块
def visualize_scores(results):
    """雷达图展示各维度评分"""
    import matplotlib.pyplot as plt
    import numpy as np
    categories = ['KPI', '技能水平', '团队协作', '项目贡献', '领导潜力']
    N = len(categories)
    # 创建子图
    fig, axes = plt.subplots(2, 3, figsize=(15, 10))
    for idx, (detail, ax) in enumerate(zip(results['details'], axes.flat)):
        if idx >= len(results['details']):
            break
        # 找到对应员工的评分
        emp = next(e for e in system.employees if e.name == detail['name'])
        scores = [emp.scores[cat] for cat in categories]
        # 雷达图数据
        angles = np.linspace(0, 2 * np.pi, N, endpoint=False).tolist()
        scores += scores[:1]
        angles += angles[:1]
        # 绘制雷达图
        ax.plot(angles, scores, 'o-', linewidth=2)
        ax.fill(angles, scores, alpha=0.25)
        ax.set_xticks(np.linspace(0, 2 * np.pi, N, endpoint=False))
        ax.set_xticklabels(categories)
        ax.set_ylim(0, 100)
        ax.set_title(f"{detail['name']} - Rank {detail['ranking']}")
    plt.tight_layout()
    plt.savefig('employee_radar.png')
    print("📊 雷达图已保存: employee_radar.png")

代码特点说明

这个案例综合了很多Python核心知识点:

  1. 面向对象编程:Employee类和PromotionSystem类
  2. 数据处理:使用Pandas和NumPy
  3. 文件操作:JSON和Excel文件导出
  4. 算法实现:排序、过滤、统计计算
  5. 模拟预测:蒙特卡洛模拟
  6. 数据可视化:Matplotlib图表
  7. 异常处理:可以增强健壮性
  8. 模块化设计:不同职责分离

运行结果示例

🚀 员工晋级评估系统启动
------------------------------
==================================================
🎯 晋级评估结果
==================================================
张伟 (技术部) - 第1名
总分: 91.23
状态: ✅ 晋级
规则检查:
  - 总分达标: ✓
  - 工作年限: ✓
  - 单项最低: ✓
  - 领导潜力: ✓
...
==================================================
📊 统计分析
==================================================
平均分: 84.56
中位数: 86.20
标准差: 5.12
最高分: 91.23
最低分: 78.45

这个案例实现了真实的评估逻辑,包含了丰富的业务规则和数据分析功能,很适合用来综合练习Python技能。

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