三级菜单(4) 函数优化

函数优化

# -*- coding: utf-8 -*-
# @Author: oppend
# @Date:   2017-07-31 21:00:25
# @Last Modified by:   oppend
# @Last Modified time: 2017-08-02 22:08:46
# 三级菜单,省市县,增删改查
def write_file(old,new):
    with open('data','w') as write_file:
        write_file.write(str(parrent_layer[0]).replace(old,new))
        write_file.flush()

parrent_layer = {}
with open('data','r') as read_file:
    menu = eval(read_file.read().strip())
    current_layer = menu
    layer_num = 0
    while True:
        for province in current_layer:
            print(province)
        choice = input('[b]上级[a]增加[d]删除[e]修改[q]退出:')
        if choice in current_layer:
            parrent_layer[layer_num] = current_layer
            layer_num += 1
            current_layer = current_layer[choice]
        elif choice == 'b':
            if parrent_layer:
                layer_num -= 1
                current_layer = parrent_layer.pop(layer_num)
            else:
                print('已经是最上级')
        elif choice == 'a':
            add_choice = input('增加:')  
            before = str(current_layer)
            current_layer[add_choice] = {}
            after = str(current_layer)
            write_file(before,after)
        elif choice == 'd':
            del_choice = input('删除:')
            before = str(current_layer)
            if del_choice in current_layer:
                del current_layer[del_choice]
                after = str(current_layer)
                write_file(before,after)
            else:
                print('无法删除不存在键')
        elif choice == 'e':
            # 修改
            before = input('修改:')
            after = input('改为:')
            current_layer[after] = current_layer.pop(before)
            write_file(before,after)
        elif choice == 'q':
            break
        else:
            print('不存在')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值