python - 计算特定员工的工资总和

标签 python python-3.x

我是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)))

最佳答案

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

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

关于python - 计算特定员工的工资总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563497/

相关文章:

python - Matplotlib:如果使用关键字 sym,箱线图离群值颜色会发生变化

python - Python 2.5 中的 urllib 或 urllib2 是否支持 https?

Python Whoosh - 合并结果

python-3.x - Django addConstraints 在 Postgres 上引发 TypeError

linux - Python3 多处理 Windows 和 Linux

python - 在 Django Python 中将一个 View 重定向到另一个 View

python - 使用省略号作为文本溢出不起作用,除非文本是 "float"ed

python - 在 PyQt4 中打开文件时出现 "Cancel"错误

python - 运行 urllib 审核请求时出现无效 URL 错误

python - 在 QTextEdit 中自动添加括号或引号