1.python
目的:spa
> 實現列表中字典kay - value的遍歷code
代碼:blog
''' 循環列表中字典元素 ''' info_list = [ {'name':'zhao','age':'22','hight':'171'}, {'name':'qian','age':'23','hight':'165'}, {'name':'sun','age':'24','hight':'148'}, {'name':'li','age':'25','hight':'166'} ] # 第一種方式 index = 0 while index < len(info_list): print('name:%s\nage:%s\nhight:%s'%(info_list[index]['name'],info_list[index]['age'],info_list[index]['hight'])) index +=1 # 第二種方式 print('-'*30) for i in info_list: print('name:%s\nage:%s\nhight:%s'%(i['name'],i['age'],i['hight']))
2.ci
目的:it
> 實現城市信息遍歷顯示(循環字典中列表信息)io
''' 城市信息展現 (省市級聯顯示) 第一種--使用for循環---- ''' dict_city = {'陝西':['西安','咸陽','榆林','銅川'], '河南':['鄭州','開封','安陽','商丘'], '湖北':['武漢','黃岡','周口','禹州']} for i in dict_city.keys(): print('----',i,'----') for val in dict_city[i]: print('|-',val) ''' 城市信息展現 (省市級聯顯示) 第二種--使用迭代器---- ''' dict_city = {'陝西':['西安','咸陽','榆林','銅川'], '河南':['鄭州','開封','安陽','商丘'], '湖北':['武漢','黃岡','周口','禹州']} dict_iter = iter(dict_city) dict_val = iter(dict_city.values()) while True: try: pro_name = next(dict_iter) print('--%s--'%pro_name) val = next(dict_val) val_name = iter(val) while True: try: print('|--%s'%next(val_name)) except StopIteration: print('--'*20) break except StopIteration: print('結束') break
運行結果:for循環
E:\python_VS_code\directory[目錄]>D://py3.6//python.exe e:/python_VS_code/directory[目錄]/demo0801/py_for.py ---- 陝西 ---- |- 西安 |- 咸陽 |- 榆林 |- 銅川 ---- 河南 ---- |- 鄭州 |- 開封 |- 安陽 |- 商丘 ---- 湖北 ---- |- 武漢 |- 黃岡 |- 周口 |- 禹州 E:\python_VS_code\directory[目錄]>D://py3.6//python.exe e:/python_VS_code/directory[目錄]/demo0801/py_flie.py --陝西-- |--西安 |--咸陽 |--榆林 |--銅川 ---------------------------------------- --河南-- |--鄭州 |--開封 |--安陽 |--商丘 ---------------------------------------- --湖北-- |--武漢 |--黃岡 |--周口 |--禹州 ---------------------------------------- 結束
====結果相似======class