[关闭]
@myles 2018-04-23T16:49:10.000000Z 字数 1117 阅读 628

第2章作业

老男孩基础


在此输入正文

  1. if __name__ == '__main__':
  2. current_dict = dic
  3. parent_lst = [] #将父级key值放入到列表中
  4. flags = False #设置标志位
  5. while not flags:
  6. for key in current_dict:
  7. print(key)
  8. choose = str(raw_input("请选择,输入b返回上一级菜单,输入q退出菜单:")).strip()
  9. if choose in current_dict:
  10. # parent_lst.append(current_dict) #将当前的状态放入列表中
  11. current_dict = current_dict[choose]
  12. elif choose == 'b':
  13. if parent_lst:
  14. current_dict = parent_lst.pop() # 什么内容被删除了
  15. elif choose == 'q':
  16. flags = True
  17. else:
  18. print("\033[34;1m输入有误,请重新输入\033[0m")

字典的逐层遍历实现

  1. # 第一层字典读取
  2. for key in new_dic:
  3. print(key)
  4. # 第二层字典读取
  5. user_choice_key = input("输入二层字典索引:")
  6. for key in new_dic[user_choice_key]:
  7. print(key)
  8. # 第三层字典读取
  9. user_choice_key = input(输入三层字典索引:)
  10. for key in new_dic[北京][user_choice_key]:
  11. print(key)

以上字典内容的逐层读取,有么有什么特点呢?

第1个特点:都是使用for循环来遍历字典中的key值;
第2个点的:就是每次遍历的字典内容(dic)一直在变,每一层字典的选择都是通过用户输入的来确定遍历的字典对象的;

所以归纳以上2个特点,我可以想到;
这个数据结构,我们可以通过一个for循环配合不断变化的字典列表来实现不同级别数据的读取,即归纳为:
(1) for 循环遍历
(2) 不断变化的字典

  1. # 遍历一节菜单key值
  2. for key in new_dic:
  3. print(key)
  4. # 用户菜单选择
  5. user_choice_key = input("用户菜单选择输入:")
  6. # 根据将用户输入一级菜单(二级数据的key)赋值生成新的二级菜单数据字典。
  7. new_dic = new_dic[user_choice_key] # 取出value(二层数据字典)复制个新字典new_dic

菜单的逐层退出实现

菜单的逐层退出可以通过一个空列表[]+append()+pop()方法来实现;

lst = []
lst.append() 存储新查询的内容;
lst.pop() 删除最近新查询而增加的列表元素内容;

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注