数据结构:
menu = {
‘北京‘:{
‘海淀‘:{
‘五道口‘:{
‘soho‘:{},
‘网易‘:{},
‘google‘:{}
},
‘中关村‘:{
‘爱奇艺‘:{},
‘汽车之家‘:{},
‘youku‘:{},
},
‘上地‘:{
‘百度‘:{},
},
},
‘昌平‘:{
‘沙河‘:{
‘老男孩‘:{},
‘北航‘:{},
},
‘天通苑‘:{},
‘回龙观‘:{},
},
‘朝阳‘:{},
‘东城‘:{},
},
‘上海‘:{
‘闵行‘:{
"人民广场":{
‘炸鸡店‘:{}
}
},
‘闸北‘:{
‘火车站‘:{
‘携程‘:{}
}
},
‘浦东‘:{},
},
‘山东‘:{},
}
需求:
可依次选择进入各子菜单
可从任意一层往回退到上一层
可从任意一层退出程序
所需新知识点:列表、字典
method1:循环实现
# -*- coding: utf-8 -*-
current_layer = menu #设置初值 parent_layer = [] #保留当前层 while True: for i in current_layer: print(i) #打印当前菜单 choice = input("请输入选择项,输入b|B返回上一级,输入q|Q则退出:").strip() if choice in current_layer: parent_layer.append(current_layer) #将当前的状态放入列表中 current_layer = current_layer[choice] #换掉菜单,进入下一层,实现循环 elif choice == ‘b‘ or choice == ‘B‘: if parent_layer: #判断是否为空 current_layer = parent_layer.pop() #取出当前层 else : print("已经到最顶层了!") elif choice == ‘q‘ or choice == ‘Q‘: break
method2:递归实现
# -*- coding: utf-8 -*-
def select_menu(dic) : for i in dic : print(i) choice = input("请输入选择项,输入b返回上一级,输入q则退出:").strip() if choice == ‘b‘ and dic != menu : return elif choice == ‘q‘ : exit() else : if choice in dic : select_menu(dic[choice]) select_menu(dic) select_menu(menu)
原文:https://www.cnblogs.com/limetloveblog/p/9406478.html