1.比较复杂的写法,但是逻辑很清晰,基本都能看的懂 代码重复多
memu={
"湖南":{
"长沙":{
"浏阳市":{
"北乡":3434,
"东乡":1212,
"南乡":4454,
"西乡":564
},
"宁乡市":{
"花明楼":678,
"东湖塘":344,
"白马桥":98
},
"天心区":{
"金盆岭":768,
"书院路":456
},
"开福区":{
"伍家岭":234,
"四方坪":789
},
"岳麓区":{
"橘子洲":6789,
"洋湖":4567
}
},
"株洲市":{},
"湘潭市":{},
"衡阳市":{},
"邵阳市":{},
"岳阳市":{},
"常德市":{},
"张家界市":{},
"益阳市":{},
"永州市":{},
"怀化市":{},
"娄底市":{},
"湘西土家族苗族自治州":{}
},
"海南":{
"海口":{
"琼山区":{
"琼山区景点":123
}
},
"三亚":{
"亚龙湾":{
"亚龙湾景点":345
}
},
"儋州":{
"詹舟":{
"詹州景点":1234
}
}
}
}
run_flag=True
while run_flag: #标志位
for i in memu:
print(i) #遍历打印第一层字典
province_choices=input("请输入省>>>")
province_list=memu.keys()
print(province_list)
if province_choices in province_list:
while run_flag:
for i in memu[province_choices]:
print(i)
city_choices=input("请输入市,按b返回上一级,按q退出")
if city_choices in memu[province_choices]:
while run_flag:
for i in memu[province_choices][city_choices]:
print(i)
zone_choices=input("请输入县,按b返回上一级,按q退出")
if zone_choices in memu[province_choices][city_choices]:
while run_flag:
for i in memu[province_choices][city_choices][zone_choices]:
print(i)
town_choices=input("请输入镇,按b返回上一级,按q退出")
if town_choices in memu[province_choices][city_choices][zone_choices]:
town_values=memu[province_choices][city_choices][zone_choices][town_choices]
print(town_values)
elif town_choices=="q":
run_flag=False
elif town_choices=="b":
pass
else:
continue
elif zone_choices=="q":
run_flag=False
elif zone_choices=="b":
break
else:
continue
elif city_choices=="q":
break
elif city_choices=="b":
break
else:
continue
elif province_choices=="q":
run_flag=False
else:
continue
2第二种方法 简单易懂重复代码少
能回退到每一层
current_layer=memu
level=[]
while True:
for k in current_layer:
print(k)
choices=input("请输入>>或者q退出,或者b返回上一层")
if choices in current_layer:
level.append(current_layer)
# print(level)
current_layer=current_layer[choices]
elif choices=="b":
if len(level)>0:
current_layer=level.pop()
else:
print("已经第一层了")
elif choices== 'q':
exit("程序结束")
else:
continue
3.只回退一层
只能回到上一层
# current_layer=memu
# last_layer=memu
# while True:
# for k in current_layer:
# print(k)
# choices=input("请输入>>>>").strip()
# if choices in current_layer: #memu[湖南]
# last_layer=current_layer #在进入下一层之前前层,保存当前层
# current_layer=current_layer[choices] #memu[湖南][长沙]
# elif choices=="b":
# current_layer=last_layer
# elif choices=="q":
# exit("程序退出")
# else:
# continue