python学习之递归打印菜单

菜单打印的装逼方式:递归打印

数据结构

menus = [
    {
        'text': '北京',
        'children': [
            {'text': '朝阳', 'children': []},
            {'text': '昌平', 'children': [
                {'text': '沙河', 'children': []},
                {'text': '回龙观', 'children': []},
            ]},
        ]
    },
    {
        'text': '上海',
        'children': [
            {'text': '宝山', 'children': []},
            {'text': '金山', 'children': []},
        ]
    }
]

实现代码

def search_menu(menus,search=None):
    if search is None:
        for x in menus:
            print(x['text'])
        search = input('请输入相应名称.:').strip()
    for i in menus:
        if search != i['text']:
            continue
        print('查询到%s'%(i['text']))
        if 'children' in i.keys():
            search_menu(i['children'])

search_menu(menus)

小结

递归函数的用处非常多,如果用的好能够节省大量的代码。

但是要记住,递归函数一定要有明确的结束条件,不然就成死循环了!

shunzi
  • 本文由 发表于 2018-03-1200:02:33
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
deepin linux 15.11系统安装 Linux

deepin linux 15.11系统安装

Deepin 15.11系统安装 window系统实在是太难用了,用了那么多linux系统,发现deepin系统真的是太好用了!特别推荐一下!!! 首先下载deepin系统ISO镜像,https://...
Python中字典的value是列表的运用 BLOG

Python中字典的value是列表的运用

今天群里一个朋友问了一个python问题,将列表a里的内容 转换成列表b那种格式,示例如下 a= 转换成: b= 简单来说 就是统计相同schema跟table的内容合并到一个list里面 一开始一直...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: