要求:
1.运行程序输出第一级菜单
2.选择一级菜单某项,输出二级菜单,同理输出三级菜单
3.输入出错重新选择
4.进入每一层支持返回上一级和退出
5.入最后一层提醒
menu = {
'001': {
'011': {
'111': (1,1,1),
'211': (2,2,2),
'311': (3,3,3)
},
'021': {
'121': (4,4,4),
'211': (5,5,5),
'311': (6,6,6)
},
'031': {
'131': (7,7,7),
'231': (8,8,8),
'331': (9,9,9)
}
},
'002': {
'012': {
'112': 'aaa',
'212': 'bbb',
'312': 'ccc'
},
'022': {
'122': 'ddd',
'222': 'eee',
'322': 'fff'
},
'032': {
'132': 'ggg',
'232': 'hhh',
'332': 'iii'
}
},
'003': {
'013': {
'113': [1, 1, 1],
'213': [2, 2, 2],
'313': [3, 3, 3]
},
'023': {
'123': [4, 4, 4],
'223': [5, 5, 5],
'323': [6, 6, 6]
},
'033': {
'133': [7, 7, 7],
'233': [8, 8, 8],
'333': [9, 9, 9]
}
}
}
current_layer = menu # 当前所在的菜单层级,类型为字典
layers = [] # 用于放置当前层级的父级,方便返回找回上一层级的key列表
while True:
print('-------------------------------------------\n')
print(f"Choice: {', '.join(current_layer.keys())} 【返回/b, 退出/q】")
choice = input(">>> ").strip() # 避免错误输入,去除输入字符串前后空格等
if not choice:
print("Error: 没有输入!!!")
continue
elif choice == 'q':
exit()
elif choice == 'b':
if not layers: # 规避第一层时,temp中没有存储的父节点
print("Error: 已经是最外层,无法返回!!!")
continue
else:
current_layer = layers.pop() # 取出列表最后一个元素,作为父级
elif choice in current_layer.keys():
if not isinstance(current_layer[choice], dict): # 第三层,因为是最后一层,继续往下没有字典结构嵌套,所以需要规避
print(f"{choice} : {current_layer[choice]}")
print('Note: 已经第三层了,无法进入下一层级了哦')
continue
layers.append(current_layer)
current_layer = current_layer[choice]
else:
print(f"Error: 输入有误,请在列表中选择【返回/b, 退出/q, {' ,'.join(current_layer.keys())}】!!!")