1 # -*- encoding:utf-8 -*- 2 import itertools 3 4 5 def main(): 6 # chain 7 print(list(itertools.chain([1,2,3], (3,4,5)))) 8 # count(start=0, step=1) 9 for item in itertools.count(2, 2): 10 print item 11 if item == 10: 12 break 13 # ifilter(contintion,data) 14 print(list(itertools.ifilter(lambda x : x%2, [1,2,3,4,5,6,7,8,9]))) 15 # filterfalse(contintion,data) 16 print(list(itertools.ifilterfalse(None,[1,2,0,1,0,3]))) 17 print(list(itertools.ifilterfalse(lambda x : x%2, [1,2,3,4,5,6,7,8,9]))) 18 print(list(itertools.ifilterfalse(lambda x : x < 20, (20, 30, 22, 40, 19, 1)))) 19 # compress() 20 print(list(itertools.compress([1,0,1], ["a","b","c"]))) 21 # starmap(func, []) 22 print(list(itertools.starmap(max,[[1,2,3],[2,3,4],[3,6,9]]))) 23 # repeat(object[, times]) 24 print(list(itertools.repeat("repeat", 5))) 25 # dropwhile(func, seq );当函数f执行返回假时, 开始迭代序列 26 print(list(itertools.dropwhile(lambda x: x<3, [1,2,3,4,5,6]))) 27 # takewhile(func, seq );当函数f执行返回假时, 停止迭代序列 28 print(list(itertools.takewhile(lambda x: x>4, [1,2,3,4,5,6]))) 29 # islice(seq[, start], stop[, step]); 30 print(list(itertools.islice(itertools.count(10), 5))) 31 print(list(itertools.islice("1234567890", 1, 8, 2))) 32 # cycle(seq, times) 33 print(list(itertools.islice(itertools.cycle("abc"), 8))) 34 # 建一个迭代器,生成项imap(fn, [], []) 35 print(list(itertools.imap(lambda x,y:"imap: "+str(x)+"+"+str(y), [2,2,2], [3,3,3,4]))) 36 # product(iter1,iter2, ... iterN, [repeat=1]) 37 # 创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数 38 for i in itertools.product([1,2,3], [4,5,6], [7,8,9], repeat=1): 39 print i 40 for i in itertools.product([1,2,3], [4,5,6], repeat=2): 41 # for i in itertools.product([1,2,3], [4,5,6], [1,2,3], [4,5,6], repeat=1): 42 print i 43 # permutations(p[,r]);返回p中任意取r个元素做排列的元组的迭代器 44 for i in itertools.permutations([1, 2, 3], 3): 45 print i 46 # combinations(iterable,r);创建一个迭代器,返回iterable中所有长度为r的子序列, note:不带重复 47 print(list(itertools.combinations([1,2,3], 2))) 48 # combinations_with_replacement() 带重复 49 print(list(itertools.combinations_with_replacement([1,2,3], 2))) 50 # tee(iterable [, n])-> (<itertools.tee object at 0x0288CAA8>, <itertools.tee object at 0x0288CAD0>, ...) 51 t1 = itertools.tee([1,2,3], 2)[1] 52 for i in t1: 53 print i 54 55 56 if __name__ == '__main__': 57 main()