You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数问题:如何处理月度工时最高员工的并列情况?

月度员工评选:处理并列最高工时的情况

我有一组以元组形式存储的员工月度工时数据,希望根据月度最高工时评选月度员工。但当前代码仅能返回最后一个并列的员工,如何修改函数以包含所有并列的员工?

原代码

work_hours = [("Abby",400),("Billy",500),("Cassie",700),("David",700)]

def employee_check(work_hours):

    current_max_hours = 0           
    employee_of_the_month = ""
    
    for a,b in work_hours:
        if b >= current_max_hours:
            employee_of_the_month = a
            current_max_hours = b
        
        else:
            pass
    
    return (employee_of_the_month,current_max_hours)

employee_check(work_hours)

当前输出

('David', 700)

修改方案

核心思路是把存储月度员工的变量从单个字符串改成列表,这样就能容纳多个并列的员工。具体修改如下:

work_hours = [("Abby",400),("Billy",500),("Cassie",700),("David",700)]

def employee_check(work_hours):
    current_max_hours = 0           
    employee_of_the_month = []  # 改为空列表
    
    for name, hours in work_hours:
        if hours > current_max_hours:
            # 发现更高工时,清空列表并添加当前员工,更新最高工时
            employee_of_the_month = [name]
            current_max_hours = hours
        elif hours == current_max_hours:
            # 工时与最高持平,直接加入列表
            employee_of_the_month.append(name)
        # 工时更低则跳过
    
    return (employee_of_the_month, current_max_hours)

print(employee_check(work_hours))

修改后输出

(['Cassie', 'David'], 700)

这样就能返回所有工时并列最高的员工了。

内容的提问来源于stack exchange,提问作者Bhumi Khandelwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:22:36