本文實例講述了Python中itertools模塊用法,分享給大家供大家參考。具體分析如下:
一般來說,itertools模塊包含創(chuàng)建有效迭代器的函數(shù),可以用各種方式對數(shù)據(jù)進行循環(huán)操作,此模塊中的所有函數(shù)返回的迭代器都可以與for循環(huán)語句以及其他包含迭代器(如生成器和生成器表達式)的函數(shù)聯(lián)合使用。
chain(iter1, iter2, ..., iterN):
給出一組迭代器(iter1, iter2, ..., iterN),此函數(shù)創(chuàng)建一個新迭代器來將所有的迭代器鏈接起來,返回的迭代器從iter1開始生成項,知道iter1被用完,然后從iter2生成項,這一過程會持續(xù)到iterN中所有的項都被用完。
from itertools import chaintest = chain('AB', 'CDE', 'F')for el in test: print elABCDEF
chain.from_iterable(iterables):
一個備用鏈構(gòu)造函數(shù),其中的iterables是一個迭代變量,生成迭代序列,此操作的結(jié)果與以下生成器代碼片段生成的結(jié)果相同:
>>> def f(iterables): for x in iterables: for y in x: yield y>>> test = f('ABCDEF')>>> test.next()'A'>>> from itertools import chain>>> test = chain.from_iterable('ABCDEF')>>> test.next()'A'
combinations(iterable, r):
創(chuàng)建一個迭代器,返回iterable中所有長度為r的子序列,返回的子序列中的項按輸入iterable中的順序排序:
>>> from itertools import combinations>>> test = combinations([1,2,3,4], 2)>>> for el in test: print el (1, 2)(1, 3)(1, 4)(2, 3)(2, 4)(3, 4)
count([n]):
創(chuàng)建一個迭代器,生成從n開始的連續(xù)整數(shù),如果忽略n,則從0開始計算(注意:此迭代器不支持長整數(shù)),如果超出了sys.maxint,計數(shù)器將溢出并繼續(xù)從-sys.maxint-1開始計算。
cycle(iterable):
創(chuàng)建一個迭代器,對iterable中的元素反復執(zhí)行循環(huán)操作,內(nèi)部會生成iterable中的元素的一個副本,此副本用于返回循環(huán)中的重復項。
dropwhile(predicate, iterable):
創(chuàng)建一個迭代器,只要函數(shù)predicate(item)為True,就丟棄iterable中的項,如果predicate返回False,就會生成iterable中的項和所有后續(xù)項。
def dropwhile(predicate, iterable): # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 iterable = iter(iterable) for x in iterable: if not predicate(x): yield x break for x in iterable: yield x
groupby(iterable [,key]):
創(chuàng)建一個迭代器,對iterable生成的連續(xù)項進行分組,在分組過程中會查找重復項。
如果iterable在多次連續(xù)迭代中生成了同一項,則會定義一個組,如果將此函數(shù)應用一個分類列表,那么分組將定義該列表中的所有唯一項,key(如果已提供)是一個函數(shù),應用于每一項,如果此函數(shù)存在返回值,該值將用于后續(xù)項而不是該項本身進行比較,此函數(shù)返回的迭代器生成元素(key, group),其中key是分組的鍵值,group是迭代器,生成組成該組的所有項。
|
新聞熱點
疑難解答
圖片精選