标签:
>>> 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
>>> 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)
标签:
原文地址:http://www.cnblogs.com/wakey/p/4249810.html