http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: Python/Ruby
2011-09-29 22:53:52
>>> print 'hello' ,'liyuan'
hello liyuan
5.2 一些迭代工具
1 并行迭代
>>> names=['anne','beth','george','damon']
>>> ages=[12,45,32,102]
>>> for i in range(len(names)):
print names[i], 'is',ages[i],'years'
anne is 12 years
beth is 45 years
george is 32 years
damon is 102 years
+++++++++++++++++++++++++++++++++++++++++++++
而内建的zip函数可以用来进行并行迭代,可以把两个序列“压缩”在一起,然后返回一个元组的列表:
>>> zip(names,ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
+++++++++++++++++++++++++++++++++++++++++++++
编号迭代:
版本1
版本2:使用内建的enumerate函数
>>> sorted([3,6,4,9,1])
[1, 3, 4, 6, 9]
>>> sorted('hello,world')
[',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('hello,world'))
['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed('hello,world'))
'dlrow,olleh'
soreed方法返回列表,reversed方法返回一个可迭代对象。可在for循环以及join方法中使用,但不能直接对它使用索引、分片以及调用list方法,如果希望进行上述处理,那么可以使用list类型转换返回的对象,上面的例子已经给出具体的做法。
+++++++++++++++++++++++++++++++++++++
for与else结合的使用方法,用于包含break的语句中,如果没从break中跳出,则执行else的语句
from math import sqrt
for n in range(99,81,-1):
root=sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it"
++++++++++++++++++++++++++++++++++++++++++
列表推导式:
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
girls=['alice','bernice','clarice']
boys=['chris','arnold','bob']
letters={}
for girl in girls:
letters.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letters[b[0]]]
++++++++++++++++++++++++++++++++++++
上述算法有个漏洞,g in letters[b[0]]有可能出错,改进的方法为:
girls=['alice','bernice','clarice']
boys=['chris','arnold','bob']
letters={}
for girl in girls:
letters.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letters.get(b[0])]
exec 的用法
+++++++++++++++++++++++++++++++++++++++++++
eval的用法
续上图的右边