python itertools的使用

来源:互联网 发布:蓝天远程网络教育 编辑:程序博客网 时间:2024/04/29 03:49


转自:http://blog.csdn.net/xiaocaiju/article/details/6968123

1. chain的使用
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4. for item in  itertools.chain(listone,listtwo):  
  5.     print item  
输出:a b c 11 22 abc

2. count的使用

    
[python] view plaincopyprint?
  1. i = 0  
  2. for item in itertools.count(100):  
  3.     if i>10:  
  4.         break  
  5.     print item,  
  6.     i = i+1  
  7.       
功能:从100开始数10个数,cout返回一个无界的迭代器,小菜鸟我不会控制了,就引入了一个计数I,让它计数10次。。
输出:100 101 102 103 104 105 106 107 108 109 110

3.cycle的使用
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4.   
  5. for item in itertools.cycle(listone):  
  6.     print item,  
打印出a b c a b c a b c a b c a b c a b c a b c a b c a b c...
功能:从列表中取元素,到列表尾后再从头取...
无限循环,因为cycle生成的是一个无界的失代器

4.ifilter的使用
ifilter(fun,iterator)
返回一个可以让fun返回True的迭代器,
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4.   
  5. def funLargeFive(x):  
  6.     if x > 5:  
  7.         return True  
  8.       
  9. for item in itertools.ifilter(funLargeFive,range(-10,10)):  
  10.     print item,  

结果:6 7 8 9

5. imap的使用
imap(fun,iterator)
返回一个迭代器,对iterator中的每个项目调用fun
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4. listthree = [1,2,3]  
  5. def funAddFive(x):  
  6.     return x + 5  
  7. for item in itertools.imap(funAddFive,listthree):  
  8.     print item,  
返回:6 7 8  对listthree中的元素每个加了5后返回给迭代器

6.islice的使用
islice()(seq, [start,] stop [, step])
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4. listthree = listone + listtwo  
  5. for item in itertools.islice(listthree,3,5):  
  6.     print item,  
功能:返回迭代器,其中的项目来自 将seq,从start开始,到stop结束,以step步长切割后
打印出:11 22

7.izip的使用
izip(*iterator)
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. listtwo = ['11','22','abc']  
  4. listthree = listone + listtwo  
  5. for item in itertools.izip(listone,listtwo):  
  6.     print item,  
结果:('a', '11') ('b', '22') ('c', 'abc')
功能:返回迭代器,项目是元组,元组来自*iterator的组合


8. repeate
repeate(elem [,n])
[python] view plaincopyprint?
  1. import itertools  
  2. listone = ['a','b','c']  
  3. for item in itertools.repeat(listone,3):  
  4.     print item,  

结果:['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c']

0 0