转自:http://blog.csdn.net/xiaocaiju/article/details/6968123
1. chain的使用
输出:a b c 11 22 abc
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- for item in itertools.chain(listone,listtwo):
- print item
2. count的使用
- i = 0
- for item in itertools.count(100):
- if i>10:
- break
- print item,
- i = i+1
输出:100 101 102 103 104 105 106 107 108 109 110
3.cycle的使用
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- for item in itertools.cycle(listone):
- print item,
功能:从列表中取元素,到列表尾后再从头取...
无限循环,因为cycle生成的是一个无界的失代器
4.ifilter的使用
ifilter(fun,iterator)
返回一个可以让fun返回True的迭代器,
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- def funLargeFive(x):
- if x > 5:
- return True
- for item in itertools.ifilter(funLargeFive,range(-10,10)):
- print item,
结果:6 7 8 9
5. imap的使用
imap(fun,iterator)
返回一个迭代器,对iterator中的每个项目调用fun
返回:6 7 8 对listthree中的元素每个加了5后返回给迭代器
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = [1,2,3]
- def funAddFive(x):
- return x + 5
- for item in itertools.imap(funAddFive,listthree):
- print item,
6.islice的使用
islice()(seq, [start,] stop [, step])
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = listone + listtwo
- for item in itertools.islice(listthree,3,5):
- print item,
打印出:11 22
7.izip的使用
izip(*iterator)
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = listone + listtwo
- for item in itertools.izip(listone,listtwo):
- print item,
功能:返回迭代器,项目是元组,元组来自*iterator的组合
8. repeate
repeate(elem [,n])
- import itertools
- listone = ['a','b','c']
- for item in itertools.repeat(listone,3):
- print item,
结果:['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c']