用一个列表来确定for循环的范围
>>> x = [0,1,2,3,4] >>> for i in x: print i, 0 1 2 3 4
循环一个字符串
>>> x = 'python' >>> for i in x: print i, p y t h o n
元组for循环
>>> x = [('http','https'),('java','python')] >>> for (a,b) in x: print (a,b) ('http', 'https') ('java', 'python')
迭代器
# 文件迭代器,读取文件的最佳实践 >>> for line in open('test.txt'): print line.upper() HELLO,WORD! # 字典迭代器 >>> testDict = {'name':'ethon','aender':'male'} >>> for key in testDict: print key + ':' + testDict[key] aender:male name:ethon
迭代协议:有一些函数可以在支持迭代协议的对象上运行
>>> testList = [9,8,7,6,5] >>> print sorted(testList) [5, 6, 7, 8, 9] >>> print sum(testList) 35 >>> print any(testList) True >>> print list(open('test.txt')) ['Hello,word!'] >>> print tuple(open('test.txt')) ('Hello,word!',)
# 元组、列表的构造函数以及join都可以对支持迭代协议的对象操作 >>> print ('--').join(open('test.txt')) Hello,word!
使用range函数来产生循环的范围
>>> for i in range(5): print str(i)+ 'is the current value' 0 is the current value 1 is the current value 2 is the current value 3 is the current value 4 is the current value
zip拉链:使用zip函数可以把两个列表合并起来,成为一个元组的列表。
>>> L1 = [1,3,5,7] >>> L2 = [2,4,6,8] >>> print zip(L1,L2) [(1, 2), (3, 4), (5, 6), (7, 8)] >>> for (a,b) in zip(L1,L2): print (a,b) (1, 2) (3, 4) (5, 6) (7, 8)
可变嵌套循环
ns = int(raw_input("How many lines of starts do you want? ")) st = int(raw_input("How many start do you want? ")) for line in range(0,ns): # 外循环 for star in range(0,st): # 内循环 print "*", print
-------------------------------------------
How many lines of starts do you want? 3
How many start do you want? 5
* * * * *
* * * * *
* * * * *