首页 > 解决方案 > 计算特定员工的工资总和

问题描述

我是python的新手,目前正在处理一个作业问题,它要求我根据salary_records列表计算员工的薪水

如果用户输入比利,它将输出比利十二个月的工资总和。如果输入的不是员工姓名,则输出[name] not found。

我的问题是我无法打印 [name] not found 并想寻求帮助,非常感谢!这是我现在得到的。

salary_records = ['Billy 12300 11700 11100 10300 10400 14800 14900 13600 12300 14600 13500 14900\n', 
              'Betty 11900 11800 15000 13000 12500 14000 11500 11100 12400 10900 20000 10300\n', 
              'Apple 13600 13700 10900 11900 12000 14900 13600 12400 11700 13700 10300 13900\n', 
              'Kelly 11400 11600 14400 10800 12700 14900 13300 12700 11900 13800 11800 13500\n', 
              'Gigi 14400 12400 11600 11600 12800 13600 11500 14300 13200 10200 14400 14400\n']

a=[]

n=input()

for i in salary_records:
    c = i.split( )

    if c[0] == n:
        a.append(c[1:13])
        c.sort(key=lambda x: x)
        del c[-1]
        c = list(map(int, c))
        print(n+' earns ' + str(sum(c)))

标签: pythonpython-3.x

解决方案


我们需要将您的字符串列表转换为字典,将名称映射到他们的工资总和。我们将去除周围的空白,然后将每个字符串拆分为单词。然后我们将数值相加并形成映射

salary_records = map(str.strip, salary_records)
salary_records = map(str.split, salary_records)
salary_records = {name: sum(map(int, months)) for name, *months in salary_records}

def get_salary(name):
    if name in salary_records:
        return salary_records[name]
    else:
        raise KeyError("Name {} not found".format(name))

get_salary('Billy')
# 154400

推荐阅读