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

Python中如何对齐合并employeeName与employeeSold列表实现员工销售排名

Python员工销量排名功能实现方案

你当前的问题核心是三个列表互相独立,单独对销量列表排序会破坏姓名和销量的对应关系,我们可以通过zip()函数将姓名和对应销量绑定后再排序,修改后的完整代码如下:

def employee():
  employeeName = input("What is Employee's name?: ")
  employeeID = input("What is Employee's ID?: ")
  employeeSold = int(input("How many houses employee sold?: "))
  nameList.append(employeeName)
  idList.append(employeeID)
  soldList.append(employeeSold)
  nextEmployee = input("Add another employee? Type Yes or No: ")
  # 原逻辑判断条件和输入提示不匹配,这里调整为输入yes时继续添加员工,可按需修改
  if nextEmployee.lower() == "yes":
    employee()
  else:
    print("Employee Names:")
    print(", ".join(nameList))
    print("Employee's ID: ")
    print(", ".join(idList))
    print("Employee Sold:")
    print( " Houses, ".join( repr(e) for e in soldList ), "Houses" )
    print("Commission: ")
    employeeCommission = [i * 500 for i in soldList]
    print(", ".join( repr(e) for e in employeeCommission ), "" )
    print("Commission Evaluation: ")
    totalCommission = sum(employeeCommission)
    print(totalCommission)
    # 排名功能实现部分
    print("Employee Ranking: ")
    # 按索引位置绑定销量和对应员工姓名
    paired_list = list(zip(soldList, nameList))
    # 按销量降序排序
    paired_list.sort(reverse=True, key=lambda x: x[0])
    print("Ranking:")
    for sold, name in paired_list:
        print(f"{name} - {sold}")

nameList = []
idList = []
soldList = []

employee()

核心逻辑说明

  • zip(soldList, nameList)会按两个列表的索引位置一一配对,生成(销量, 姓名)格式的元组,确保销量和对应员工的绑定关系不会错乱
  • 排序时指定key=lambda x:x[0]表示以元组的第一个元素(销量)为排序依据,reverse=True实现从高到低的降序排列
  • 遍历排序后的元组集合,直接输出对应格式的排名内容即可完全匹配你需要的输出效果

内容的提问来源于stack exchange,提问作者Kieran Spencer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:54:01