
分析:此题目考虑到了字典,元组等数据,用字典比较好实现一些。
难点一:可随时返回上一级
思考中
为了方便先做三个省,每个省2个市,每个市1个县
难点二:随时退出程序。
思考中。
china_city = { "河北":{ "石家庄":{ "栾城","正定" }, "衡水":{ "枣强","武邑" } }, "黑龙江省":{ "哈尔滨":{ "五常","木兰" }, "佳木斯":{ "同江","东风" } }, "广西省":{ "南宁":{ "江南","马山" }, "玉林":{ "玉州","兴业" } } } def city_print(sheng,shi): sheng_namber = 0 sheng_key = list(china_city.keys()) if sheng == 0 and shi == 0: for i in china_city.keys(): print(i) elif sheng !=0 and shi ==0 : sheng_zhi = sheng_key[sheng-1] for i in china_city[sheng_zhi].keys(): print(i) shiqu = int(input("请输入你要查询的市区编码》》》")) if shiqu>=1 and shiqu<3: shi_zhi = china_city[sheng_zhi] shi_key = list(shi_zhi.keys()) print(shi_zhi[shi_key[shiqu -1]]) else: print("看好在选择哦,请重新选择") judge = True while judge == True: print("欢迎使用全国城市遍历系统!".center(50,"*")) for i in china_city.keys(): print(i) shengfen = int(input("请输入你要查询的省份编码》》》")) shiqu = 0 city_print(shengfen,shiqu)
目前退出还没写
china_city = { "河北":{ "石家庄":{ "栾城","正定" }, "衡水":{ "枣强","武邑" } }, "黑龙江省":{ "哈尔滨":{ "五常","木兰" }, "佳木斯":{ "同江","东风" } }, "广西省":{ "南宁":{ "江南","马山" }, "玉林":{ "玉州","兴业" } } } def quits(): import os print("感谢使用,再见!") os._exit(0) def city_print(sheng,shi): sheng_namber = 0 sheng_key = list(china_city.keys()) if sheng == 0 and shi == 0: for i in china_city.keys(): print(i) elif sheng !=0 and shi ==0 : sheng_zhi = sheng_key[sheng-1] for i in china_city[sheng_zhi].keys(): print(i) shiqu = int(input("请输入你要查询的市区编码,退出请输入123》》》")) if shiqu>=1 and shiqu<3: shi_zhi = china_city[sheng_zhi] shi_key = list(shi_zhi.keys()) print(shi_zhi[shi_key[shiqu -1]]) elif shiqu == 123: quits() else: print("看好在选择哦,请重新选择") judge = True while judge == True: print("欢迎使用全国城市遍历系统!".center(50,"*")) for i in china_city.keys(): print(i) shengfen = int(input("请输入你要查询的省份编码,退出请输入123》》》")) shiqu = 0 if shengfen == 123: quits() city_print(shengfen,shiqu)

1 china_city = { 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 } 27 def quits(): 28 import os 29 print("感谢使用,再见!") 30 os._exit(0) 31 current_layer = china_city #拿出字典 32 parent_layer = [] #保存所有父级,最后一个元素永远都是父级 33 while True: 34 for key in current_layer: 35 print(key) 36 choice = input(">>>").strip() 37 if len(choice) == 0:continue 38 39 if choice in current_layer: 40 parent_layer.append(current_layer)#在进入下一层之前,把当前层(也就是下一层父级) 41 #下一层loop.当用户选择b的选择,就可以直接取列表的最后一个值出来就ok 42 current_layer = current_layer[choice]#改成了子层 43 elif choice == "b": 44 if parent_layer: 45 current_layer = parent_layer.pop() 46 elif choice == "q": 47 quits() 48 else: 49 print("无此项!")