计算特定员工的薪金总和

时间:2018-11-30 19:11:15

标签: python python-3.x

我是python的新手,目前正在处理任务分配问题,它要求我根据列表salary_records计算员工的薪水

如果用户输入Billy,它将输出Billy十二个月的薪水总和。 如果输入的不是工作人员的姓名,则会输出[找不到]。

我的问题是我无法打印[找不到],想寻求帮助,非常感谢!这就是我现在所拥有的。

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

2 个答案:

答案 0 :(得分:6)

我们需要将您的字符串列表转换成将名称映射到其薪金总额的字典。我们将去除周围的空格,然后将每个字符串拆分为单词。然后,我们将数字值加在一起并形成映射

Actors

答案 1 :(得分:2)

您可以标记以检查人员是否存在:

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()
found_name = False
for i in salary_records:
    c = i.split( )

    if c[0] == n:
        found_name = True
        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)))
if not found_name:
    print('%s not found' % n)

此外,要将薪水与姓名分开,您只需删除第一个元素:

if c[0] == n:
    found_name = True
    del c[0]
    c = list(map(int, c))
    print(n + ' earns ' + str(sum(c)))
相关问题