如果项目不在列表中,则输出“未找到”

时间:2018-12-01 11:06:32

标签: python python-3.x list

我目前正在从事一个项目,并且在这里停留了几个小时... 我被要求找出那位特定员工赚钱最多的月份 如果人员在列表中,它会很好地工作,但是,如果人员不在列表中,它就不会工作。

这就是我现在得到的...

salary = ['Ken 1230 2170 1110 1030 1040 1480 1490 1360 1230 1460 1350 1490\n', 
                  'Shi 1190 1180 1500 1300 1250 1400 1150 1110 1240 2090 2000 1030\n', 
                  'John 1360 1370 1090 1190 1200 1490 1360 1240 1170 1370 1030 1390\n', 
                  'Mary 1140 1160 1440 1080 1270 2490 1330 1270 1190 1380 1180 1350\n', 
                  'Bernice 1440 2240 1160 1160 1280 1360 1150 1430 1320 1020 2400 2400\n']
salary = map(str.strip, salary)
salary = map(str.split, salary)
maxlist=[]
month=[]
n=input('Which staff?')
dict_month = {0:'January',1:'February',2:'March',3:'April',4:'May',5:'June',6:'July',7:'Augest',8:'September',9:'October',10:'November',11:'December'}
found_name = False

for i in salary:
    if i[0] == n:
        found_name = True
        del i[0]
        i = list(map(int, i))
        max_value = max(i)
        for j,k in enumerate(i):
            if k == max_value:
                maxlist.append(j)
for i in maxlist:
    if i in dict_month:
        month.append(dict_month[i])

if len(month)==1:
    print(n+' earns the most in '+ month[0])
else:
    print(n + " earns the most in " + ", ".join(month[:-1]) + " and " + month[-1] )

if not found_name:
    print('%s not found' % n)

2 个答案:

答案 0 :(得分:1)

问题是您还是要检查列表月份,您需要更早使用found_name

if found_name:
    if len(month)==1:
        print(n+' earns the most in '+ month[0])
    else:
        print(n + " earns the most in " + ", ".join(month[:-1]) + " and " + month[-1] )
else:
    print('%s not found' % n)

如果找不到名称,则没有month[-1]

答案 1 :(得分:1)

您应该将错误处理纳入代码中:

try:
    if len(month)==1:
        print(n+' earns the most in '+ month[0])
    else:
        print(n + " earns the most in " + ", ".join(month[:-1]) + " and " + month[-1] )
except IndexError:
    print('%s not found' % n)

现在,当用户输入意外的输入时,程序不会崩溃:

Which staff? JOHN DOE
 JOHN DOE not found
>>>