python模块之itertools

一、啥是itertools模块?————创建高效循环的迭代器的方法

  这个模块标准化了一系列快速,可用的,内存高效工具。构造了一个迭代器世界。

二、无穷迭代器

 

IteratorArgumentsResultsExample
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') --> ...
repeat() elem [,n] elem, elem, elem, ... endlessly or up to n times 无穷或者n次 repeat(10, 3) --> 10 10 10

 

 

 

 

 

 

三、以输入最短的终止

 

Iterator

Arguments

Results

Example

accumulate()

p [,func]

p0, p0+p1, p0+p1+p2, ... 前面的数据求和

accumulate([1,2,3,4,5]) --> 10 15

chain()

p, q, ...

p0, p1, ... plast, q0, q1, ... 将参数的所有数据,依次打印

chain('ABC', 'DEF') --> F

chain.from_iterable()

iterable

p0, p1, ... plast, q0, q1, ... 和上面的好像没区别

chain.from_iterable(['ABC', 'DEF']) --> F

compress()

data, selectors

(d[0] if s[0]), (d[1] if s[1]), ... 如果右边为True,左边的对应元素就显示

compress('ABCDEF', [1,0,1,0,1,1]) --> F

dropwhile()

pred, seq

seq[n], seq[n+1], starting when pred fails 左边的失败时,开始显示相应的元素

dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 1

filterfalse()

pred, seq

elements of seq where pred(elem) is false 过滤哪些判断语句失败的

filterfalse(lambda x: x%2, range(10)) --> 8

groupby()

iterable[, keyfunc]

sub-iterators grouped by value of keyfunc(v)

 按照key分组成几个迭代器

islice()

seq, [start,] stop [, step]

elements from seq[start:stop:step] 将可迭代对象进行切片

islice('ABCDEFG', 2, None) --> G

starmap()

func, seq

func(*seq[0]), func(*seq[1]), ... 将右边的数据,依次调用左边func

starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 1000

takewhile()

pred, seq

seq[0], seq[1], until pred fails 执行左边直到失败

takewhile(lambda x: x<5, [1,4,6,4,1]) --> 4

tee()

iterable, n

it1, it2, ... itn splits one iterator into n 

 tee管道,将一个iterable对象转换成n个相同的iterator对象

zip_longest()

p, q, ...

(p[0], q[0]), (p[1], q[1]), ... 按照最长的进行zip操作

zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C-D-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

三、组合迭代

IteratorArgumentsResults
product() 笛卡尔积 p, q, ... [repeat=1] cartesian product, equivalent to a nested for-loop
permutations() 排列 p[, r] r-length tuples, all possible orderings, no repeated elements
combinations() 组合,不显示重复的 p, r r-length tuples, in sorted order, no repeated elements
combinations_with_replacement() 组合显示重复的 p, r r-length tuples, in sorted order, with repeated elements
product('ABCD', repeat=2)   AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)   AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)   AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2)   AA AB AC AD BB BC BD CC CD DD

 

posted @ 2017-06-06 19:39  skiler  阅读(237)  评论(0)    收藏  举报