python迭代器模組itertools常用方法
阿新 • • 發佈:2020-07-19
itertools是python中內建的一種高效的生成各種迭代器或者是類的模組,這些函式的返回值為一個迭代器,經常被用在for迴圈中,當然,也可直接使用next()方法取值,今天就來說說itertools中的常用方法.
itertools按照迭代器的功能可分為三類:
- 無限迭代器: 生成一個無限序列,比如自然數序列 1, 2, 3, 4, …
- 有限迭代器: 接收一個或多個序列(sequence)作為引數,進行組合、分組和過濾等;
- 組合迭代器: 序列的排列、組合,求序列的笛卡兒積等
無限迭代器
itertools.count(start=0, step=1)
1
|
itertools.count(start=0, step=1)
|
itertools.cycle(iterable)
1
|
itertools.cycle(iterable)
|
itertools.repeat(object[, times])
1
|
itertools.repeat(object[, times])
|
有限迭代器
itertools.chain(iterable1, iterable2, …)
1
|
itertools.chain(iterable1, iterable2, ...)
|
itertools.chain.from_iterable(iterable)
1
|
itertools.chain.from_iterable(iterable)
|
itertools.compress(data, selectors)
1
|
itertools.compress(data, selectors)
|
itertools.dropwhile(predicate, iterable)
1
|
itertools.dropwhile(predicate, iterable)
|
itertools.takewhile(predicate, iterable)
1
|
itertools.takewhile(predicate, iterable)
|
itertools.ifilter(predicate, iterable)
1
|
itertools.ifilter(predicate, iterable)
|
itertools.ifilterfalse(predicate, iterable)
1
|
itertools.ifilterfalse(predicate, iterable)
|
itertools.groupby(iterable[, key])
1
|
itertools.groupby(iterable[, key])
|
itertools.islice(iterable, stop)
1
|
itertools.islice(iterable,[start], stop,[step])
|
itertools.imap(func, iter1, iter2, iter3, …)
1
|
imap(func, iter1, iter2, iter3, ...)
|
itertools.izip(*iterables)
1
|
itertools.izip(*iterables)
|
itertools.izip_longest(*iterables, [fillvalue=None])
1
|
itertools.izip_longest(*iterables,[fillvalue=None])
|
組合迭代器
itertools.product(*iterables[, repeat])
1
|
itertools.product(*iterables[, repeat])
|
itertools.permutations(iterable[, r])
1
|
itertools.permutations(iterable[, r])
|
itertools.combinations(iterable, r)
1
|
itertools.combinations(iterable, r)
|
itertools.combinations_with_replacement(iterable, r)
1
|
itertools.combinations_with_replacement(iterable, r)
|