python循环技巧
2013-05-04 20:04
288 查看
在字典中循环时,关键字和对应的值可以使用items()方法同时解读出来。
>>>dict={1:2,'a':'b','hello':'world'}
>>>dict.values()
['b',2,'world']
>>>dict.keys()
['a',1,'hello']
>>>dict.items()
[('a','b'),(1,2),('hello','world')]
>>>
遍历字典的几种方法:
在序列中循环时,索引位置和对应值可以使用enumerate()函数同时得到。
同时循环两个或更多的序列,可以使用zip()整体解读。
>>>knights={'gallahad':'thepure','robin':'thebrave'} >>>fork,vinknights.items(): ...printk,v ... gallahadthepure robinthebrave 字典的格式以{key:value}的格式来定义 比如 a={'name':'xiaoming','age':23} 字典支持嵌套 下面介绍的操作方法用到的例子是: a={'name':'xiaoming','age':23} Python的字典的items(),keys(),values()都返回一个list
>>>dict={1:2,'a':'b','hello':'world'}
>>>dict.values()
['b',2,'world']
>>>dict.keys()
['a',1,'hello']
>>>dict.items()
[('a','b'),(1,2),('hello','world')]
>>>
遍历字典的几种方法:
#!/usr/bin/python dict={"a":"apple","b":"banana","o":"orange"} print"##########dict######################" foriindict: print"dict[%s]="%i,dict[i] print"###########items#####################" for(k,v)indict.items(): print"dict[%s]="%k,v print"###########iteritems#################" fork,vindict.iteritems(): print"dict[%s]="%k,v print"###########iterkeys,itervalues#######" fork,vinzip(dict.iterkeys(),dict.itervalues()): print"dict[%s]="%k,v
在序列中循环时,索引位置和对应值可以使用enumerate()函数同时得到。
>>>fori,vinenumerate(['tic','tac','toe']):
...printi,v
...
0tic
1tac
2toe
同时循环两个或更多的序列,可以使用zip()整体解读。
>>>questions=['name','quest','favoritecolor']
>>>answers=['lancelot','theholygrail','blue']
>>>forq,ainzip(questions,answers):
...print'Whatisyour%s?Itis%s.'%(q,a)
...
Whatisyourname?Itislancelot.
Whatisyourquest?Itistheholygrail.
Whatisyourfavoritecolor?Itisblue.
相关文章推荐
- Python数据结构的一些技巧、数据结构练习、循环与判断练习题
- Python的for和break循环结构中使用else语句的技巧
- Python学习笔记:循环技巧
- python 循环技巧
- Python减少循环层次和缩进的技巧分析
- Python列表生成器的循环技巧分享
- Python的for和break循环结构中使用else语句的技巧
- Python减少循环层次和缩进的技巧分析
- Python学习笔记-数据结构之循环技巧
- Python循环的技巧
- python函数定义中的参数问题、循环技巧
- Python实用技巧---列表推导式(轻量级循环)与map
- python 循环技巧
- Python笔记7:循环技巧和控制语句
- Python -- 循环技巧(Looping Techniques)
- python循环技巧
- 【python技巧系列】在循环中处理异常并继续运行
- Python列表生成器的循环技巧分享
- python循环技巧
- python进阶教程之循环对象