Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。

count 创建一个迭代器,生成从n开始的连续整数,如果忽略n,则从0开始计算(注意:此迭代器不支持长整数)

如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算

import itertools
for item in itertools.count(1,3):
      if item>20:
       break
      print(item)
...
1
4
7
10
13
16
19
>>>

传入一个序列,无限循环下去:
import itertools
its=["a","b","c","d"]
for item in itertools.cycle(its):
    print (item)
a
b
c
d
a
b
.
.
.

创建一个迭代器,重复生成object,times(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象。
import itertools
its=["a","b","c"]
for item in itertools.repeat(its,4):
    print (item)

itertools.chain(*iterables)
*iterables为一个或多个可迭代序列
作用:返回所有可迭代序列

import itertools
its=["a","b","c","d"]
hers=["A","B","C","D"]
others=["1","2","3","4"]
for item in itertools.chain(its,hers,others):
    print (item)
...
a
b
c
d
A
B
C
D
1
2
3
4

[2] compress
itertools.compress(data, selectors)
data为数据对象
selectors为选择器(规则)
作用:返回数据对象中对应规则为True的元素
import itertools

its=["a","b","c","d","e","f","g","h"]
selector=[True,False,1,0,3,False,-2,"y"]
for item in itertools.compress(its,selector):
    print (item)
...
a
c
e
g
h

[x for x in filter(None,range(2,10))]
list(filter(None,range(2,10)))
chain.from_iterable()
将单个iterable中的所有元素拼接输出。
d=['串一株幸运草','串一个同心圆']
for i in itertools.chain.from_iterable(d):
    print(i)
...











dropwhile()
itertools.dropwhile(predicate, iterable)
从头开始,干掉不符合的元素,直到第一个正确元素。    
for i in itertools.dropwhile(lambda x:x<7,[1,2,3,6,7,8,2,4,5,9]):
   print(i)
...
7
8
2
4
5
9

filterfalse()
输出为错的要素:
for i in itertools.filterfalse(lambda x:x=='moyu',['moyu','jinye']):
    print(i)
...
jinye

groupby()
itertools.groupby(iterable, key=None)
将iterable同要素聚合输出:
for k,g in itertools.groupby('aaAAaBBBCCCCC'):
    print(k)
    print(list(g))
...
a
['a', 'a']
A
['A', 'A']
a
['a']
B
['B', 'B', 'B']
C
['C', 'C', 'C', 'C', 'C']

islice()
切片操作的迭代器版本
>>> for i in itertools.islice('fengliutitangShawn',0,None,2):
...     print(i)
...
f
n
l
u
i
a
g
h
w

tee()
itertools.tee(iterable, n=2)
创建n个与iterable相同的独立迭代器。
for i in itertools.tee([1,2,3,4,5,6]):
    for j in i:
        print(j)
...
1
2
3
4
5
6
1
2
3
4
5
6

组合生成器
product()
itertools.product(*iterables[,repeat=1])
对*iterables进行笛卡尔积运算
for i in itertools.product('Tom','Jerry',repeat=1):
    print(i)
...
('T', 'J')
('T', 'e')
('T', 'r')
('T', 'r')
('T', 'y')
('o', 'J')
('o', 'e')
('o', 'r')
('o', 'r')
('o', 'y')
('m', 'J')
('m', 'e')
('m', 'r')
('m', 'r')
('m', 'y')

05-13 07:41