三级菜单的实现

三级菜单:
1. 运行程序输出第一级菜单
2. 选择一级菜单某项,输出二级菜单,同理输出三级菜单
3. 返回上一级菜单和顶部菜单
4. 菜单数据保存在文件中

首先创建一个菜单文件menu用来存放需要显示的数据

 1 {
 2     '北京':{
 3         '西城区':{
 4             '西单':{
 5                 '大悦城':{},
 6                 '明珠':{},
 7                 '君太':{},
 8             },
 9             '中南海':{}
10         },
11         '朝阳区':{
12             '三里屯':{
13                 '优衣库':{},
14                 '太古里':{},
15                 '工体':{},
16             },
17             '国贸':{
18                 '银泰中心':{},
19                 '万达广场':{},
20                 '北京电视台':{},
21             },
22         },
23         '海淀区':{
24             '五道口':{
25                 '搜狐':{},
26                 'google':{},
27             },
28             '中关村':{
29                 '爱奇艺':{},
30                 '汽车之家':{},
31                 '优酷':{},
32             },
33             '上地':{
34                 '百度':{},
35             },
36         },
37         '昌平区':{
38             '沙河':{
39                 '老男孩':{},
40                 '北航':{},
41             },
42             '天通苑':{},
43             '回龙观':{},
44         },
45     },
46     '上海':{
47         '闵行':{
48             "人民广场":{
49                 '炸鸡店':{}
50             }
51         },
52         '闸北':{
53             '火车战':{
54                 '携程':{}
55             }
56         },
57         '浦东':{},
58     },
59     '广州':{
60         '越秀区':{},
61         '天河区':{
62             '体育中心'
63             '海心沙'
64             '花城广场'
65         },
66         '黄浦区':{
67             '黄埔军校':{},
68         },
69     },
70 }
menu

实现代码如下:

 1 with open("menu",encoding="utf8") as f: #从文件中获取菜单文本
 2     menu_str = f.read()
 3     menu = eval(menu_str) #将字符串类型转换成语句
 4 
 5 current_layer =menu
 6 last_layer = []
 7 while True:
 8     for key in current_layer:
 9         print(key)
10     choice =input("请选择要去往的地点【退回上一层B】【退出Q】:
>>>>").strip()  #用户输入
11     if not choice: continue
12     if choice == 'q':  #退出循环
13         print("退出成功!")
14         break
15     elif choice in current_layer:   #判断是否在当前层
16         last_layer.append(current_layer) #采用列表里面嵌套字典的结果!
17         current_layer = current_layer[choice]  #进到下一层
18     elif choice.lower() == 'b':  #退入到上一层目录
19         if last_layer:
20             current_layer = last_layer[-1]
21             last_layer.pop()
22         else:
23             print('当前处在起始层!')
24     else:
25         print('您输入的地点或操作有误,请重新选择!')
26         continue

  整个程序最精髓的地方是使用了列表里嵌套字典的数据结构来解决分层的问题!通过这个小程序,感受到字典结构在解决问题上确实非常方便,而且逻辑非常合理。

原文地址:https://www.cnblogs.com/sl-swift/p/7808859.html