menu = { "安徽": { "六安": { "金寨": [], "舒城": [], "霍山": [], }, "淮南": { "田家庵": [], "凤台": [], "寿县": [], } }, "江苏": { "无锡": { "宜兴": [], "江阴": [] }, "南京": { "鼓楼": [], "玄武": [], "雨花": [], }, }, } # 堆栈方法 l = [menu] while l: for k in l[-1]:print(k) key = input("input>>>") if key in l[-1].keys() and l[-1][key]: l.append(l[-1][key]) elif key == "b": l.pop() elif key == "q": break else: continue
2.递归方法
def threemenu(menu): 递归 while True: for k in menu:print(k) key = input("please input your choice:").strip() if key == "b" or key == "q": return key elif key in menu.keys() and menu[key]: ret = threemenu(menu[key]) if ret == "q": return "q"
第三种方法
current_layer = menu back_flag = False quit_flag = False while 1: for key in current_layer: print(key) choice = input(">>>:").strip() if len(choice) == 0: continue if choice in current_layer: current_layer = current_layer[choice] elif choice == "q": break elif choice == "b": pass else: print("无此项")