用递归和堆栈方法分别实现三级菜单

递归实现

dic_three = {'北京':{'昌平':{'沙河':{}}},'山东':{'济南':{}}}
def three(dic):
    while 1:
        for i in dic:
            print(i)
        k = input('>>>').strip()
        if k == 'b'or k =='q':return k
        elif k in dic.keys() and dic[k]:
            ret = three(dic[k])
            if k == 'q':
                return q
        elif(not dic.key(k)) or (not dic(k)):
            continue

three(dic_three)

堆栈实现

dic = {'北京':{'昌平':{'沙河':{}}},'山东':{'济南':{}}}
l = [dic]
while l:
    for key in l[-1]:print(key)
    k = input('input>>>').strip()
    if k in l[-1].keys() and l[-1][k]:
        l.append(l[-1][k])
    elif k == 'b':
        l.pop()
    elif k == 'q':
        break
    else:
        continue
原文地址:https://www.cnblogs.com/li33232/p/11498695.html