> 文档中心 > 05 字典与集合应用总结

05 字典与集合应用总结


任务1:统计需要取快递人员的名单

i=0instr = "xiaohao"# 创建保存取快递人员的集合past = set()# 如果字符串只包含数字则返回 True 否则返回 False。while not str.isdigit(instr):    setlen = len(past)    if setlen >= 5: print("人员已满") break    instr = input("请输入收到快递人员的名单:")    if not str.isdigit(instr): past.add(instr) if setlen == len(past):     print("\033[41;39m      取快递人员已存在!!   \33[0m")     continue    i=i+1print("需要通知取快递的人员名单有:" +str(i) + "\n"+ "\n".join(past))

05 字典与集合应用总结

任务2:手机通讯录管理程序

import osphonedic = {}  # 保存电话本的字典choice = 9     # 存储用户选择菜单数字isfind = 0     # 存储是否查找到联系人电话print("STAR通讯录功能: 1:添加联系人   2:删除联系人 \  3:查找联系人   4:电话本显示\n")if os.path.isfile("phonedic.txt"): # 判断某一对象(需提供绝对路径)是否为文件    if os.path.getsize("phonedic.txt"): # 获得文件的大小(字节) file = open("phonedic.txt", 'r') for line in file:     line.strip()  # 去掉字符串左右的空格和特殊符号     if len(line) < 12:  # 联系人和联系人电话合计长度要超过1位  liststr = line.split(",")  phonedic[liststr[0]] = liststr[1] print("目前已录入的联系人电话:\n" + "\n".join(phonedic)) file.close()while choice != 0:  # 输入数字0时退出系统    choice = input("请输入您要操作菜单的数字:")    if choice.isdigit(): if int(choice) == 1:  # 添加联系人     name = input("请输入联系人姓名:")     while len(name) == 0:  print("输入非法,请重新输入!")  name = input("请输入联系人姓名:")     phone = input("请输入联系人电话:")     while len(phone) < 6:  # 电话位数尾号为6位  print("输入非法,请重新输入!")  phone = input("请输入联系人电话:")     phonedic[phone] = name     file = open("phonedic.txt", 'w')     if os.path.getsize("phonedic.txt"):  file.truncate()     for item in phonedic.items():  file.writelines(item[0] + "," + item[1] + "\n")     file.close()     print("\033[1;32m    联系人已成功保存到通讯录!!   \33[0m") if int(choice) == 2:  # 删除联系人     name = input("请输入要删除联系人的电话:")     while len(name) == 0:  print("输入非法,请重新输入!")  name = input("请输入要删除联系人的电话:")     if name in phonedic:  del phonedic[name]  file = open("phonedic.txt", 'w')  if os.path.getsize("phonedic.txt"):      file.truncate()  for item in phonedic.items():      file.writelines(item[0] + "," + item[1] + "\n")  file.close()  print("\033[1;32m    联系人 " + name + " 已删除!!   \33[0m")  print("目前通讯录中保存的联系人电话:\n" + "\n".join(phonedic))     else:  print("\033[1;32m    通讯录中不存在要删除的联系人!   \33[0m") if int(choice) == 3:  # 查找联系人     name = input("请输入要查找的联系人的电话:")     while len(name) == 0:  print("输入非法,请重新输入!")  name = input("请输入要查找的联系人的电话:")     isfind = 0     for item in phonedic.items():  if name == item[0]:      isfind = 1      print("您要查找的联系人是:\n" + item[0] + "   " + item[1])     if isfind == 0:  print("\033[1;32m    通讯录中不存在要查找的联系人!   \33[0m") if int(choice) == 4:  # 显示联系人及电话     print(" 电话联系人  ")     for item in phonedic.items():  print(item[0] + "    " + item[1])    else: print("输入非法,请重新输入!") choice = input("请输入您要操作菜单的数字:")

05 字典与集合应用总结