三級菜單

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '網易':{},
                'google':{}
            },
            '中關村':{
                '愛奇藝':{},
                '汽車之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龍觀':{},
        },
        '朝陽':{},
        '東城':{},
    },
    '上海':{
        '閔行':{
            "人民廣場":{
                '炸雞店':{}
            }
        },
        '閘北':{
            '火車戰':{
                '攜程':{}
            }
        },
        '浦東':{},
    },
    '山東':{},
}

一、每一層判斷

tag=True
while tag:
    menu1=menu
    for key in menu1: # 打印第一層
        print(key)

    choice1=input('第一層>>: ').strip() # 選擇第一層

    if choice1 == 'b': # 輸入b,則返回上一級
        break
    if choice1 == 'q': # 輸入q,則退出整體
        tag=False
        continue
    if choice1 not in menu1: # 輸入內容不在menu1內,則繼續輸入
        continue

    while tag:
        menu_2=menu1[choice1] # 拿到choice1對應的一層字典
        for key in menu_2:
            print(key)

        choice2 = input('第二層>>: ').strip()

        if choice2 == 'b':
            break
        if choice2 == 'q':
            tag = False
            continue
        if choice2 not in menu_2:
            continue

        while tag:
            menu_3=menu_2[choice2]
            for key in menu_3:
                print(key)

            choice3 = input('第三層>>: ').strip()
            if choice3 == 'b':
                break
            if choice3 == 'q':
                tag = False
                continue
            if choice3 not in menu_3:
                continue

            while tag:
                menu_4=menu_3[choice3]
                for key in menu_4:
                    print(key)

                choice4 = input('第四層>>: ').strip()
                if choice4 == 'b':
                    break
                if choice4 == 'q':
                    tag = False
                    continue
                if choice4 not in menu_4:
                    continue

                # 第四層內沒數據了,無需進入下一層



二、精簡版

layers=[menu,]
while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)
    choice=input('>>: ').strip()
    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break
    if choice not in current_layer:continue
    layers.append(current_layer[choice])


三、另一種

def three_menu(dic):
    while True:
        for k in dic:print(k)
        key=input('>>: ').strip()
        if key == "b" or key=="q":return key
        elif key in dic.keys() and dic[key]:
            ret = three_menu(dic[key])
            if ret =="q": return "q"
        elif (not dic.get(key)) or (not dic[key]):
            continue
three_menu(menu)





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章