itertools模块
itertools模块概览
+生成无限迭代器
- count(start, [step]) #从start开始,步长为step的无限整数迭代器(step默认值为1)
- cycle(iterable) #不断循环iterable而得到的无限迭代器
- repeat(object, [n]) #重复object对象n次生成的迭代器 (n默认值为无穷大)
+处理输入序列得到新的迭代器
- chain(*iterables) #将多个序列串联
- compress(data, selectors) #依据selector选择data中的某些元素
- islice(iterable, [start],stop,[step]) #获取序列的切片
- groupby(iterable, [key]) #按照key进行分组
- tee(iterable, [n=2]) #生成iterable的n个独立迭代器
- ----------------------
- dropwhile(predicate, iterable) #返回第一次使predicate为False之后的所有元素
- takewhile(predicate, iterable) #返回第一次使predicate为False之前的所有元素
- ifilter(func, iterable) #提取使function为True的所有元素
- ifilterfalse(func, iterable) #提取使function为False的所有元素
- imap(func, *iterables) #生成func在*iterables所定义的定义域对应的值域,其中func每一个参数来自于对应的序列
- starmap(func, iterable) #功能同上,只是func的每一个参数对应iterable的一个元素
- izip(*iterables) #收集所有序列每一维的元素,作为迭代器的一个元素(以最短的序列为准)
- izip_longest(*iterables, [fillvalue]) #功能同上,(以最长的为准)
+组合迭代器
- product(*iterable) #生成以笛卡尔积元组所构成的迭代器
- permutations(iterable, [r]) #生成由iterable所有排列构成的迭代器,(r为每一个排列的长度)
- combinations(iterable, r) #生成由iterable所有组合构成的迭代器,r为每一组合的长度
- combinations_with_replacement(iterable, r) #功能同上,(*带重复)
实例
无限迭代器:
1. count(start, [step])
2. cycle(iterable)
3. repeat(object, [n])
迭代器 参数 结果 count() start, [step] start, start+step, start+2*step, ... count(10) --> 10 11 12 13 14 ... cycle() p p0, p1, ... plast, p0, p1, ... cycle('ABCD') --> A B C D A B C D ... repeat() elem [,n] elem, elem, elem, ... endlessly or up to n times repeat(10, 3) --> 10 10 10
处理输入序列:
1. chain(*iterables)
1 from itertools import chain 2 3 for item in chain([1,2,3], 'abc'): 4 print item 5 6 #输出: 7 1 8 2 9 3 10 a 11 b 12 c
2. compress(data, selectors)
1 from itertools import compress 2 3 data = ['A','B','C','D','E','F'] 4 for item in compress(data, [0,1,1,0,1,0]): 5 print item 6 7 #结果: 8 B 9 C 10 E
3. islice(iterable, [start], stop, [step])
1 from itertools import islice 2 3 lst = [1,2,3,4,5] 4 5 '''只限定结束位置:''' 6 for item in islice(lst, 2): 7 print item 8 9 #结果: 10 1 11 2 12 13 '''限定开始和结束:''' 14 for item in islice(lst, 2, 4): 15 print item 16 17 #结果: 18 3 19 4 20 21 '''限定步长:''' 22 for item in islice(lst, 0, 5, 2): 23 print item 24 25 #结果: 26 1 27 3 28 5
4. groupby(iterable, [key])
from itertools import groupby from operator import itemgetter lst = ['aa','bb', 'abc','bcd', 'abcd'] for k,sub in groupby(lst, len): print k, list(sub) #结果: 2 ['aa', 'bb'] 3 ['abc','bcd'] 4 ['abcd'] d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) di = sorted(d.iteritems(), key=itemgetter(1)) #需要按key先进性排序,否则达不到效果 for k,sub in groupby(di, key=itemgetter(1)): print k, list(sub) #结果: 1 [('a', 1), ('c', 1), ('e', 1)] 2 [('b', 2), ('d', 2), ('f', 2)] 3 [('g', 3)]
5. tee(iterable, [n=2])
from itertools import tee lst = [1,2,3,4,5] >>> for item in tee(lst): print list(item) #结果: [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] >>> for item in tee(lst, 4): print list(item) #结果: [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
浙公网安备 33010602011771号