首先非常感謝11期的學長薜保庫提供了一種非常實用函數遞歸方法,讓實現三層菜單如此簡單,不過對所遍歷的嵌套字典或列表格式有所要求。有特定的環境下非常實用。 主要針對中國的各省市區進行展示,採用了百度的js介面: http://passport.baidu.com/js/site...
首先非常感謝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'],",", print 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)遞歸調用