首先按照自己的想法写出来
menu = {
'北京': {
'朝阳': {
'国贸': {
'CCC': {},
'HP': {},
'CCTV': {},
},
},
'昌平': {
'昌平': {
'天通苑': {},
},
},
'海淀': {
'默默': {
'陌陌': {},
},
'五道口': {
'快手': {},
}
},
},
'上海': {
'浦东': {
'陆家嘴': {
'高盛': {},
},
'外滩': {},
},
'闵行': {},
},
'山东': {
'济南': {},
'德州': {
'乐林': {
'订看':{},
},
},
},
}
break_flag = False
exit_flag = False
while not break_flag and not exit_flag :
for key in menu:
print(key)
choice = input("1>>:").strip()
if choice == 'b':
break_flag = True
if choice == 'q':
exit_flag = True
if choice in menu:
while not break_flag and not exit_flag:
for key2 in menu[choice]:
print(key2)
choice2 = input("2>>:").strip()
if choice2 == 'b':
break_flag = True
if choice == 'q':
exit_flag = True
if choice2 in menu[choice]:
while not break_flag and not exit_flag:
for key3 in menu[choice][choice2]:
print(key3)
choice3 = input("3>>:").strip()
if choice2 == 'b':
break_flag = True
if choice == 'q':
exit_flag = True
if choice3 in menu[choice][choice2]:
for key4 in menu[choice][choice2][choice3]:
print(key4)
else:
break_flag = False
else:
break_flag = False
else:
break_flag = False
==========================================
如果上面的完成了!可以试试优化 因为看上去上面的代码很多地方都是重复的
menu = {
'北京': {
'朝阳': {
'国贸': {
'CCC': {},
'HP': {},
'CCTV': {},
},
},
'昌平': {
'昌平': {
'天通苑': {},
},
},
'海淀': {
'默默': {
'陌陌': {},
},
'五道口': {
'快手': {},
}
},
},
'上海': {
'浦东': {
'陆家嘴': {
'高盛': {},
},
'外滩': {},
},
'闵行': {},
},
'山东': {
'济南': {},
'德州': {
'乐林': {
'订看':{},
},
},
},
}
current_layer = menu
parent_layers = []
while True:
for key in current_layer:
print(key)
choice = input(">>:").strip()
if len(choice) == 0:continue
elif choice in current_layer:
parent_layers.append(current_layer)
current_layer =current_layer[choice]
elif choice == 'b':
if parent_layers:
current_layer = parent_layers.pop()
else:
print("input error!")