7-8. 人力资源。创建一个简单的雇员姓名和编号的程序。让用户输入一组雇员姓名和编号。你的程序可以提供按照姓名排序输出的功能,雇员姓名显示在前面,后面是对应的雇员编号。附加题:添加一项功能,按照雇员编号的顺序输出数据。
用的python3.4 排序函数sorted整了半天
特别注意的是3.4对字典的排序用的是
sorted_x = sorted(dict.<span style="color:#ff0000;">items</span>(), key=lambda a:a[0],reverse=False)
db={}
global lenb
lenb=0
def insert():
'''
负责插入数据的操作
'''
global lenb
prompt='请输入你要添加的数据:'
done=False
while not done:
try:
db[input('雇员')]=int(input('编号'))
except:
print('输入错误')
else:
done=True
lenb=lenb+1
def sort_name():
'''
按姓名排序并显示
'''
sorted_x = sorted(db.items(), key=lambda a:a[0])
for i in range(0,lenb):
print('雇员:%s 编号:%s '%(sorted_x[i][0],sorted_x[i][1]))
def sort_id():
'''
按编号排序并显示
'''
sorted_x = sorted(db.items(), key=lambda a:a[1])
for i in range(0,lenb):
print('雇员:%s 编号:%s '%(sorted_x[i][0],sorted_x[i][1]))
def manage():
'''
管理菜单
'''
prompt = """
(1)插入数据
(2)显示按姓名排序
(3)显示按编号排序
(Q)退出
Enter choice: """
done = False
while not done:
chosen = False
while not chosen:
try:
choice = input(prompt).strip()[0].lower()
except (EOFError, KeyboardInterrupt):
choice = 'q'
print ('\nYou picked: [%s]' % choice)
if choice not in '123q':
print ('invalid option, try again')
else:
if choice == 'q':
done = True
break
if choice == '2':
sort_name()
if choice == '3':
sort_id()
if choice == '1':
insert()
if __name__ == '__main__':
manage()