逐层进入和返回上一层的实现

#1   简单版  切换
goods = { '华为':{ 'A系':{'A1':[1000,1100,1200,],'A2':[2000,2100,2200,],'A3':[3000,3100,3200,],}, 'B系':{'B1':[4000,4200,4400,],'B2':[5000,5200,5400,],'B3':[6000,6200,6400,],}, 'C系':{'C1':[7000,7300,7600,],'C2':[8000,8300,8600,],'C3':[9000,9300,9600,],},}, '小米':{ 'M系':{'M1':[610,630,650,],'M2':[710,730,750,],'M3':[810,830,850,],}, 'N系':{'N1':[920,950,980,],'N2':[1020,1050,1080,],'N3':[1120,1150,1180],}, 'L系':{'L1':[1230,1270,1300,],'L2':[1430,1470,1500,],'L3':[1630,1670,1700,],},}, '魅族':{ 'X系':{'X1':[599,699,799,],'X2':[699,799,899,],'X3':[799,899,999,],}, 'Y系':{'Y1':[1099,1199,1299,],'Y2':[1299,1399,1499,],'Y3':[1499,1599,1699,],}, 'Z系':{'Z1':[2099,2199,2299,],'Z2':[2399,2499,2599,],'Z3':[2699,2799,2899,],},},} menu = [goods] while 1: for good in goods: print(good) choose = input("请选择》》》") if choose in goods: #将当前的遍历字典加入到menu列表中,方便返回时调用 menu.append(goods) #把用户选择的字典,赋值给goods goods = goods[choose] elif choose.upper()=="B": #用户选择返回上一级时,把记录列表中最后一项赋值给要循环的goods,然后再把最后一项一个字典删除 goods = menu[-1] menu.pop() elif choose.lower()=="q": break else: print("你输入有误,请重新选择")

 2.目录逐层进入和返回上一层的实现 

import os

def switch_dir(path):

    menu = [path]

    while 1:
        lst = os.listdir(path)

        for el in lst:
            print(el)

        choose = input("请选择(../表示切换到上层目录)》》》")
        if choose in lst and os.path.isdir(os.path.join(path, choose)):

            menu.append(path)
            path = os.path.join(path, choose)

        elif choose.strip() =="../":#
            path = menu[-1]

            if len(menu)==1:
                print("已经是家目录了,没有上一层目录了")
            else:
                menu.pop()

        elif choose.upper()=="Q":
            break

        else:
            print("输入有误或为非文件夹")

path = "d:\home"
switch_dir(path)

 

posted @ 2018-12-23 16:39  冰底熊  阅读(447)  评论(0编辑  收藏  举报