实现省市县三级联动
要求:
打印三级菜单
可返回上一级
可随时退出程序
1.使用字典实现
dic={
"安徽":{
"六安":{
"金寨":[],
"舒城":[],
"霍山":[],
"霍邱:[]"},
"淮南":{
"田家庵":[],
"凤台":[],
"寿县":[]
}
},
"江苏":{
"无锡":{
"宜兴":[],
"江阴":[]
},
"南京":{
"鼓楼":[],
"玄武":[],
"雨花":[]
},
},
}
#保存当前层,保持动态循坏
current_layer = dic
#保存所有父级循环
parent_layers = []
exit_flag = True
while exit_flag:
for key in current_layer:
print(key)
choice = input("<<<<").strip()
if len(choice) == 0: continue
if 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()
elif choice == 'q':
exit_flag = False
print(".....end......")
else:
print("无此项")
2.以文件存储形式实现
(1)data文件内容
{'Anhui': {'Hefei': {'FeiDong'}, 'Huainan': {'Feitai'}}, 'Tianjin': {}, 'Beijing': {'Feitai': {'B2'}, 'Chaoyang': {'B1'}}}
(2)代码实现
- 打印三级菜单
- 能实现增删改查
- 可返回上一级
- 可随时退出程序
# __author__: "Betsy Kudo"
# date: 2019/1/9
with open("data", "r", encoding="utf-8") as fr:
data = fr.readline().strip()
# 转换为字典
dic = eval(data)
# 保存当前层,保持动态循坏
current_layer = dic
# 保存所有父级循环
parent_layers = []
layer_num = 0
exit_flag = True
while exit_flag:
print("------------********----------")
for key in current_layer:
print(key)
print("------------********-----------")
print("[a]增加 [b]返回上一级 [d]删除 [u]修改 [q]停止")
choice = input("<<<<").strip()
if len(choice) == 0:
continue
if choice in current_layer:
layer_num += 1
# 当前层加到父层列表
parent_layers.append(current_layer)
# 进入下一层
current_layer = current_layer[choice]
# 增
elif choice == 'a':
add_data = input("input the data:")
current_layer[add_data] = {}
elif choice == 'b':
if parent_layers:
layer_num -= 1
# 取出父级
current_layer = parent_layers.pop()
else:
print("已是最上级")
# 删
elif choice == 'd':
del_data = input("input the data:")
if del_data in current_layer:
del current_layer[del_data]
else:
print("无法删除不存在的数据")
# 改
elif choice == 'u':
old_data = input("input the old data:")
new_data = input("input the new data:")
if old_data in current_layer:
current_layer[new_data] = current_layer.pop(old_data)
# 退出
elif choice == 'q':
exit_flag = False
print(".....end......")
else:
print("无此项")
with open("data", "w", encoding="utf-8") as fw:
# 更新文件内容
fw.write(str(current_layer))
fw.flush()