首先非常感谢11期的学长薜保库提供了一种非常实用函数递归方法,让实现三层菜单如此简单,不过对所遍历的嵌套字典或列表格式有所要求。有特定的环境下非常实用。
主要针对中国的各省市区进行展示,采用了百度的js接口:
http://passport.baidu.com/js/sitedata_bas.js
格式大概如下:
var sitedata =
[
{ name:"请选择", sub:[{name:"请选择"}], type:1},
{ name:"北京", sub:[{name:"请选择"},{name:"东城区"},{name:"西城区"},{name:"崇文区"},{name:"宣武区"},{name:"朝阳区"},{name:"海淀区"},{name:"丰台区"},{name:"石景山区"},{name:"房山区"},{name:"通州区"},{name:"顺义区"},{name:"昌平区"},{name:"大兴区"},{name:"怀柔区"},{name:"平谷区"},{name:"门头沟区"},{name:"密云县"},{name:"延庆县"},{name:"其他"}], type:0},
{ name:"广东", sub:[{name:"请选择",sub:[]},
{ name:"广州", sub:[{name:"请选择"},{name:"越秀区"},{name:"荔湾区"},{name:"海珠区"},{name:"天河区"},{name:"白云区"},{name:"黄埔区"},{name:"番禺区"},{name:"花都区"},{name:"南沙区"},{name:"萝岗区"},{name:"增城市"},{name:"从化市"},{name:"其他"}],type:0},
{ name:"深圳", sub:[{name:"请选择"},{name:"福田区"},{name:"罗湖区"},{name:"南山区"},{name:"宝安区"},{name:"龙岗区"},{name:"盐田区"},{name:"其他"}], type:0},
{ name:"珠海", sub:[{name:"请选择"},{name:"香洲区"},{name:"斗门区"},{name:"金湾区"},{name:"其他"}],type:0},
{
{ name:"汕头", sub:[{name:"请选择"},{name:"金平区"},{name:"濠江区"},{name:"龙湖区"},{name:"潮阳区"},{name:"潮南区"},{name:"澄海区"},{name:"南澳县"},{name:"其他"}],type:0},
{ name:"韶关", sub:[{name:"请选择"},{name:"浈江区"},{name:"武江区"},{name:"曲江区"},{name:"乐昌市"},{name:"南雄市"},{name:"始兴县"},{name:"仁化县"},{name:"翁源县"},{name:"新丰县"},{name:"乳源瑶族自治县"},{name:"其他"}],type:0},
}
具体代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'xuebk'
import logging
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
logger = logging.getLogger(__name__) def search_a(sitedata,search=None):
if search is None:
for x in sitedata:
print x['name'],",",
search = raw_input('请输入相应名称.:')
print "search:"+search
for i in sitedata:
if search != i['name']:
continue
print('查询到%s'%(i['name']))
if 'sub' in i.keys():
search_a(i['sub']) if __name__ == '__main__':
search_a(sitedata_bas)
递归调用