Python从零开始 day6之补充

今天优化了一下三级菜单的代码

两个版本:

一:分几次循环完成:

south_west={
'云南':{
'昆明':{'嵩明':{'杨林':[]},'五华区':[],'官渡区':[],'西山区':[]},
'曲靖':{'宣威':{'宛水':[]},'麒麟区':[],'陆良':[],'马龙':[],'富源':[]},
'大理':{'大理州区':{'古城区':'大理古城'}}
},
'贵州':{
'贵阳':{'观山湖区':{}},
'遵义':{'播州区':{}},
'六盘水':{'水城':{}}
},
'四川':{
'成都':{'天府新区':{}},
'绵阳':{'游仙区':{}},
'乐山':{'五通桥区':{}}
}
}

back_flag = False
exit_flag = False

while not back_flag and not exit_flag:
for key in south_west:
print(key)
choice = input('>>>:').strip()
if choice == 'B':
back_flag = True
if choice == 'Q':
exit_flag = True

if choice in south_west:
while not back_flag and not exit_flag:
for key1 in south_west[choice]:
print(key1)
choice1 = input('>>>:').strip()
if choice1 == 'B':
back_flag = True
if choice1 == 'Q':
exit_flag = True

if choice1 in south_west[choice]:
while not back_flag and not exit_flag:
for key2 in south_west[choice][choice1]:
print(key2)
choice2 = input('>>>:').strip()
if choice2 == 'B':
back_flag = True
if choice2 == 'Q':
exit_flag = True

if choice2 in south_west[choice][choice1]:
while not back_flag and not exit_flag:
for key3 in south_west[choice][choice1][choice2]:
print(key3)
choice3 = input('>>>:').strip()
if choice3 == 'B':
back_flag = True
if choice3 == 'Q':
exit_flag = True

if choice3 in south_west[choice][choice1][choice2]:
while not back_flag and not exit_flag:
for key4 in south_west[choice][choice1][choice2][choice3]:
print(key4)
choice4 = input('>>>:').strip()
print('last level!')
if choice4 =='B':
back_flag = True
if choice4 =='Q':
exit_flag = True
else:
back_flag = False
else:
back_flag = False
else:
back_flag = False
else:
back_flag = False



二、利用列表的特点,分别添加和删除,也就是先将上一层的数据保存到列表中待调用
south_west={
'云南':{
'昆明':{'嵩明':{'杨林':[]},'五华区':[],'官渡区':[],'西山区':[]},
'曲靖':{'宣威':{'宛水':[]},'麒麟区':[],'陆良':[],'马龙':[],'富源':[]},
'大理':{'大理州区':{'古城区':'大理古城'}}
},
'贵州':{
'贵阳':{'观山湖区':{}},
'遵义':{'播州区':{}},
'六盘水':{'水城':{}}
},
'四川':{
'成都':{'天府新区':{}},
'绵阳':{'游仙区':{}},
'乐山':{'五通桥区':{}}
}
}

current_layer = south_west
#parent_layer = []
parent_layers = []
while True:
for key in current_layer:
print(key)
chioce = input('>>>:').strip()
if len(chioce)==0:continue
if chioce in current_layer:
#parent_layer = current_layer #在进入下一层前,先将上一层记录下来(相当于是父级)
parent_layers.append(current_layer)

current_layer = current_layer[chioce] #进入下一层(相当于是子级)
elif chioce == 'b':
#current_layer = parent_layer #把父级赋值给子级
if parent_layers : #空列表返回False
current_layer = parent_layers.pop()
else:
print('无')


转载于:https://www.cnblogs.com/yubang178/p/10187970.html

你可能感兴趣的:(Python从零开始 day6之补充)