循环设计
通过range()来控制for循环,
>>> s='abcdefghijk' >>> s[0] 'a' >>> s[1] 'b' >>> for i in range(0,len(s),2): #range函数中,分别定义上限,下限,步长, ... print s[i] ... a c e g i k
enumrate()
>>> t=enumerate(s) >>> for (index,char) in t: ... print index,char ... 0 a 1 b 2 c 3 d
enumerate,每次循环中得到下标和元素
zip()
如果有多个等长序列,让后想要每次循环时从各个序列分别取出一个元素,可以用zip()
>>> x=(1,2,3) >>> y=(4,5,6) >>> z=(7,8,9) >>> for (a,b,c) in zip(x,y,z): ... print (a,b,c) ... (1, 4, 7) (2, 5, 8) (3, 6, 9)
>>> zipped=zip(x,y) #聚合 >>> print zipped [(1, 4), (2, 5), (3, 6)] >>> na,nb=zip(*zipped) #分解 >>> print(na,nb) ((1, 2, 3), (4, 5, 6)) >>> print na,nb (1, 2, 3) (4, 5, 6)