1. 程式人生 > >省市區縣,實現逐層訪問,並逐層返回!

省市區縣,實現逐層訪問,並逐層返回!

else for 返回 重新 pri 北京 app pen true

data = {
‘北京‘: {
‘朝陽‘: {},
‘海澱‘: {},
‘昌平‘: {},
},
‘上海‘: {},
‘四川‘: {
‘廣元‘:{
‘利州區‘:{},
‘昭化‘:{},
‘朝天三區‘:{},
},
‘成都‘:{
‘金牛區‘: {},
‘成華區‘: {},
‘高新區‘: {},
},
‘綿陽‘:{
‘涪城區‘: {},
‘遊仙區‘: {},
‘農科區‘: {},
},
},
}

current_layer = data
parent_layers = []
while True:
for i in current_layer: #循環字典中的key
print(i)
choice = input(‘請輸入:‘)
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‘:
current_layer = data
elif choice == ‘e‘:
exit()
else:
print(‘您的輸入有誤,請重新輸入:‘)

省市區縣,實現逐層訪問,並逐層返回!