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