三级菜单实现的几种方式
普通的写法
name = {
'北京': {
'朝阳区': {
'望京': ['cc', '大众'],
'国贸': ['宝马', '奔驰'],
'东直门': ['保洁', '业务'],
},
'海淀区': {
},
'昌平区': {
'沙河': ['默默', 'qq'],
'天通苑': ['tim', 'time'],
},
},
'安徽': {},
'湖南': {},
}
var1 = 1
while var1:
for i in name:
print(i)
print('''------温馨提示------
退出请按"q",
返回上一级请按"b",
返回首页请按"h"
--------------------''')
while True:
city_choose = input("选择1>>>")
if city_choose in name:
var2 = 1
while var2:
for i2 in name[city_choose]:
print(' ', i2)
city_choose1 = input("选择2>>>")
if city_choose1 in name[city_choose]:
var3 = 1
while var3:
for i3 in name[city_choose][city_choose1]:
print(' ', i3)
city_choose2 = input('选择我3>>>')
if city_choose2 in name[city_choose][city_choose1]:
var4 = 1
while var4:
for i4 in name[city_choose][city_choose1][city_choose2]:
print(' ', i4)
while True:
chosee = input('已到最后一层,输入你的选择>>>')
if chosee == 'q':
exit()
elif chosee == 'b':
var4 = 0
break
elif chosee == 'h':
var2 = var3 = var4 = 0
break
else:
print('输入错误请重新输入:')
if city_choose2 == 'q':
exit()
elif city_choose2 == 'b':
var3 = 0
print('--------')
elif city_choose2 == 'h':
var3 = var2 = 0
print('--------')
for i in name:
print(i)
if city_choose1 == 'q':
exit()
elif city_choose1 == 'b':
var2 = 0
print('--------')
for i in name:
print(i)
elif city_choose1 == 'h':
var2 = 0
print('--------')
for i in name:
print(i)
if city_choose == 'q':
exit()
elif city_choose == 'b':
print('已经是第一层,请重新选择')
print('--------')
for i in name:
print(i)
elif city_choose == 'h':
print('已经是第一层,请重新选择')
print('--------')
for i in name:
print(i)
递归函数实现三级菜单
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {},
'上地': {},
},
'昌平': {},
'朝阳': {},
'东城': {},
},
'安徽': {},
'湖南': {},
}
def three_menu(dic):
while True:
for city in dic:
print(city)
choose = input(">>>").strip()
if choose == 'b' or choose == 'q':
return choose
elif choose in dic.keys() and dic[choose]:
ret = three_menu(dic[choose])
if ret == 'q':
return 'q'
three_menu(menu)
堆栈实现
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {},
'上地': {},
},
'昌平': {},
'朝阳': {},
'东城': {},
},
'安徽': {},
'湖南': {},
}
l = [menu]
while True:
if not l: # 如果列表为空就直接退出
break
for city in l[-1]: # 显示最后一个元素的内容
print(city)
choose = input(">>>").strip()
if choose == 'b':
l.pop() # 要显示上一层信息就要把这一层信息从列表中删除,每次显示的信息都是最后一个元素
elif choose.lower() == 'q':
break
elif choose in l[-1].keys() and l[-1][choose]:
l.append(l[-1][choose]) # 把最新的内容加到列表最后面