天天看點

Python标準庫(1) — itertools子產品

簡介

官方描述:Functional tools for creating and using iterators.即用于建立高效疊代器的函數。

itertools.chain(*iterable)

将多個序列作為一個單獨的序列傳回。

例如:

輸出:

itertools.combinations(iterable, r)

傳回指定長度的"組合"

itertools.combinations_with_replacement(iterable, r)

傳回指定長度的“組合”,組合内元素可重複

itertools.product(*iterable[,repeat])

傳回指定長度的所有組合,可了解為笛卡爾乘積

itertools.premutations(iteravle[,r])

傳回長度為r的排列

itertools.compress(data,selector)

傳回selector為True的data對應元素

itertools.count(start=0,step=1)

傳回以start開始,step遞增的序列,無限遞增

itertools.cycle(iterable)

将疊代器進行無限疊代

itertools.dropwhile(predicate, iterable)

直到predicate為真,就傳回iterable後續資料, 否則drop掉

itertools.groupby(iterable[,key])

傳回一組(key,itera),key為iterable的值,itera為等于key的所有項

例如:

輸出:

itertools.ifilter(predicate, iterable)

傳回predicate結果為True的元素疊代器,如果predicate為None,則傳回所有iterable中為True的項

itertools.ifilterfasle(predicate,iterable)

傳回predicate為False的元素,如果predicate為None,則傳回所有iterable中為False的項

itertools.imap(function,*iterables)

相當于疊代器方式的map()

itertools.islice(iterable, start,stop[,step])

相當于疊代器方式的切片操作

itertools.repeat(object,[,times])

不停的傳回object對象,如果指定了times,則傳回times次

itertools.starmap(function,iterable)

傳回function(iter)的值,iter為iterable的元素

itertools.takewhile(predicate,iterable)

如果predicate為真,則傳回iterable元素,如果為假則不再傳回,break.

原文釋出時間為:2017-02-25