黑夜追风,arx,舒活的意思
2 :三级菜单
数据结构: menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ "人民广场":{ '炸鸡店':{} } }, '闸北':{ '火车站':{ '携程':{} } }, '浦东':{}, }, '山东':{}, } 需求: 可依次选择进入各子菜单 可从任意一层往回退到上一层 可从任意一层退出程序 所需新知识点:列表、字典
代码一:
exit_flag = false
while not exit_flag:
for i in menu:
print(i)
choice1 = input("选择进入1>>:")
if choice1 in menu:
while not exit_flag:
for i2 in menu[choice1]:
print("\t", i2)
choice2 = input("选择进入2>>:")
if choice2 in menu[choice1]:
while not exit_flag:
for i3 in menu[choice1][choice2]:
print("\t\t", i3)
choice3 = input("选择进入3>>:")
if choice3 in menu[choice1][choice2]:
for i4 in menu[choice1][choice2][choice3]:
print("\t\t", i4)
choice4 = input("最后一层,按b返回>>:")
if choice4 == "b":
pass
elif choice4 == "q":
exit_flag = true
if choice3 == "b":
break
elif choice3 == "q":
exit_flag = true
if choice2 == "b":
break
elif choice2 == "q":
exit_flag = true
代码二:(优化版本,代码缩减为15行)
current_layer = menu
parent_layer = [] # 将父级key值放入到列表中
flags = false # 设置标志位
while not flags:
for key in current_layer:
print(key)
choose = input("请选择,输入b返回上一级菜单,输入q退出菜单:").strip() # 去除空格
if choose in current_layer:
parent_layer.append(current_layer) # 将当前的状态放入列表中
current_layer = current_layer[choose]
elif choose == 'b':
if parent_layer:
current_layer = parent_layer.pop()
elif choose == 'q':
flags = true
else:
print('输入有误,请重新输入')
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论