
Python:itertools模塊
itertools模塊包含創(chuàng)建有效迭代器的函數(shù),可以用各種方式對(duì)數(shù)據(jù)進(jìn)行循環(huán)操作,此模塊中的所有函數(shù)返回的迭代器都可以與for循環(huán)語(yǔ)句以及其他包含迭代器(如生成器和生成器表達(dá)式)的函數(shù)聯(lián)合使用。
chain(iter1, iter2, ..., iterN):
給出一組迭代器(iter1, iter2, ..., iterN),此函數(shù)創(chuàng)建一個(gè)新迭代器來(lái)將所有的迭代器鏈接起來(lái),返回的迭代器從iter1開(kāi)始生成項(xiàng),知道iter1被用完,然后從iter2生成項(xiàng),這一過(guò)程會(huì)持續(xù)到iterN中所有的項(xiàng)都被用完。
1 from itertools import chain
2 test = chain('AB', 'CDE', 'F')
3 for el in test:
4 print el
5
6 A
7 B
8 C
9 D
10 E
11 F
chain.from_iterable(iterables):
一個(gè)備用鏈構(gòu)造函數(shù),其中的iterables是一個(gè)迭代變量,生成迭代序列,此操作的結(jié)果與以下生成器代碼片段生成的結(jié)果相同:
1 >>> def f(iterables):
2 for x in iterables:
3 for y in x:
4 yield y
5
6 >>> test = f('ABCDEF')
7 >>> test.next()
8 'A'
9
10
11 >>> from itertools import chain
12 >>> test = chain.from_iterable('ABCDEF')
13 >>> test.next()
14 'A'
combinations(iterable, r):
創(chuàng)建一個(gè)迭代器,返回iterable中所有長(zhǎng)度為r的子序列,返回的子序列中的項(xiàng)按輸入iterable中的順序排序:
1 >>> from itertools import combinations
2 >>> test = combinations([1,2,3,4], 2)
3 >>> for el in test:
4 print el
5
6
7 (1, 2)
8 (1, 3)
9 (1, 4)
10 (2, 3)
11 (2, 4)
12 (3, 4)
count([n]):
創(chuàng)建一個(gè)迭代器,生成從n開(kāi)始的連續(xù)整數(shù),如果忽略n,則從0開(kāi)始計(jì)算(注意:此迭代器不支持長(zhǎng)整數(shù)),如果超出了sys.maxint,計(jì)數(shù)器將溢出并繼續(xù)從-sys.maxint-1開(kāi)始計(jì)算。
cycle(iterable):
創(chuàng)建一個(gè)迭代器,對(duì)iterable中的元素反復(fù)執(zhí)行循環(huán)操作,內(nèi)部會(huì)生成iterable中的元素的一個(gè)副本,此副本用于返回循環(huán)中的重復(fù)項(xiàng)。
dropwhile(predicate, iterable):
創(chuàng)建一個(gè)迭代器,只要函數(shù)predicate(item)為T(mén)rue,就丟棄iterable中的項(xiàng),如果predicate返回False,就會(huì)生成iterable中的項(xiàng)和所有后續(xù)項(xiàng)。
1 def dropwhile(predicate, iterable):
2 # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
3 iterable = iter(iterable)
4 for x in iterable:
5 if not predicate(x):
6 yield x
7 break
8 for x in iterable:
9 yield x
groupby(iterable [,key]):
創(chuàng)建一個(gè)迭代器,對(duì)iterable生成的連續(xù)項(xiàng)進(jìn)行分組,在分組過(guò)程中會(huì)查找重復(fù)項(xiàng)。
如果iterable在多次連續(xù)迭代中生成了同一項(xiàng),則會(huì)定義一個(gè)組,如果將此函數(shù)應(yīng)用一個(gè)分類列表,那么分組將定義該列表中的所有唯一項(xiàng),key(如果已提供)是一個(gè)函數(shù),應(yīng)用于每一項(xiàng),如果此函數(shù)存在返回值,該值將用于后續(xù)項(xiàng)而不是該項(xiàng)本身進(jìn)行比較,此函數(shù)返回的迭代器生成元素(key, group),其中key是分組的鍵值,group是迭代器,生成組成該組的所有項(xiàng)。
ifilter(predicate, iterable):
創(chuàng)建一個(gè)迭代器,僅生成iterable中predicate(item)為T(mén)rue的項(xiàng),如果predicate為None,將返回iterable中所有計(jì)算為T(mén)rue的項(xiàng)。
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
ifilterfalse(predicate, iterable):
創(chuàng)建一個(gè)迭代器,僅生成iterable中predicate(item)為False的項(xiàng),如果predicate為None,則返回iterable中所有計(jì)算為False的項(xiàng)。
ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
imap(function, iter1, iter2, iter3, ..., iterN)
創(chuàng)建一個(gè)迭代器,生成項(xiàng)function(i1, i2, ..., iN),其中i1,i2...iN分別來(lái)自迭代器iter1,iter2 ... iterN,如果function為None,則返回(i1, i2, ..., iN)形式的元組,只要提供的一個(gè)迭代器不再生成值,迭代就會(huì)停止。
1 >>> from itertools import *
2 >>> d = imap(pow, (2,3,10), (5,2,3))
3 >>> for i in d: print i
4
5 32
6 9
7 1000
8
9 ####
10 >>> d = imap(pow, (2,3,10), (5,2))
11 >>> for i in d: print i
12
13 32
14 9
15
16 ####
17 >>> d = imap(None, (2,3,10), (5,2))
18 >>> for i in d : print i
19
20 (2, 5)
21 (3, 2)
islice(iterable, [start, ] stop [, step]):
創(chuàng)建一個(gè)迭代器,生成項(xiàng)的方式類似于切片返回值: iterable[start : stop : step],將跳過(guò)前start個(gè)項(xiàng),迭代在stop所指定的位置停止,step指定用于跳過(guò)項(xiàng)的步幅。與切片不同,負(fù)值不會(huì)用于任何start,stop和step,如果省略了start,迭代將從0開(kāi)始,如果省略了step,步幅將采用1.
def islice(iterable, *args):
# islice('ABCDEFG', 2) --> A B
# islice('ABCDEFG', 2, 4) --> C D
# islice('ABCDEFG', 2, None) --> C D E F G
# islice('ABCDEFG', 0, None, 2) --> A C E G
s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = next(it)
for i, element in enumerate(iterable):
if i == nexti:
yield element
nexti = next(it)
#If start is None, then iteration starts at zero. If step is None, then the step defaults to one.
15 #Changed in version 2.5: accept None values for default start and step.
izip(iter1, iter2, ... iterN):
創(chuàng)建一個(gè)迭代器,生成元組(i1, i2, ... iN),其中i1,i2 ... iN 分別來(lái)自迭代器iter1,iter2 ... iterN,只要提供的某個(gè)迭代器不再生成值,迭代就會(huì)停止,此函數(shù)生成的值與內(nèi)置的zip()函數(shù)相同。
1 def izip(*iterables):
2 # izip('ABCD', 'xy') --> Ax By
3 iterables = map(iter, iterables)
4 while iterables:
5 yield tuple(map(next, iterables))
izip_longest(iter1, iter2, ... iterN, [fillvalue=None]):
與izip()相同,但是迭代過(guò)程會(huì)持續(xù)到所有輸入迭代變量iter1,iter2等都耗盡為止,如果沒(méi)有使用fillvalue關(guān)鍵字參數(shù)指定不同的值,則使用None來(lái)填充已經(jīng)使用的迭代變量的值。
1 def izip_longest(*args, **kwds):
2 # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
3 fillvalue = kwds.get('fillvalue')
4 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
5 yield counter() # yields the fillvalue, or raises IndexError
6 fillers = repeat(fillvalue)
7 iters = [chain(it, sentinel(), fillers) for it in args]
8 try:
9 for tup in izip(*iters):
10 yield tup
11 except IndexError:
12 pass
permutations(iterable [,r]):
創(chuàng)建一個(gè)迭代器,返回iterable中所有長(zhǎng)度為r的項(xiàng)目序列,如果省略了r,那么序列的長(zhǎng)度與iterable中的項(xiàng)目數(shù)量相同:
1 def permutations(iterable, r=None):
2 # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
3 # permutations(range(3)) --> 012 021 102 120 201 210
4 pool = tuple(iterable)
5 n = len(pool)
6 r = n if r is None else r
7 if r > n:
8 return
9 indices = range(n)
10 cycles = range(n, n-r, -1)
11 yield tuple(pool[i] for i in indices[:r])
12 while n:
13 for i in reversed(range(r)):
14 cycles[i] -= 1
15 if cycles[i] == 0:
16 indices[i:] = indices[i+1:] + indices[i:i+1]
17 cycles[i] = n - i
18 else:
19 j = cycles[i]
20 indices[i], indices[-j] = indices[-j], indices[i]
21 yield tuple(pool[i] for i in indices[:r])
22 break
23 else:
24 return
product(iter1, iter2, ... iterN, [repeat=1]):
創(chuàng)建一個(gè)迭代器,生成表示item1,item2等中的項(xiàng)目的笛卡爾積的元組,repeat是一個(gè)關(guān)鍵字參數(shù),指定重復(fù)生成序列的次數(shù)。
1 def product(*args, **kwds):
2 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
3 # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
4 pools = map(tuple, args) * kwds.get('repeat', 1)
5 result = [[]]
6 for pool in pools:
7 result = [x+[y] for x in result for y in pool]
8 for prod in result:
9 yield tuple(prod)
repeat(object [,times]):
創(chuàng)建一個(gè)迭代器,重復(fù)生成object,times(如果已提供)指定重復(fù)計(jì)數(shù),如果未提供times,將無(wú)止盡返回該對(duì)象。
1 def repeat(object, times=None):
2 # repeat(10, 3) --> 10 10 10
3 if times is None:
4 while True:
5 yield object
6 else:
7 for i in xrange(times):
8 yield object
starmap(func [, iterable]):
創(chuàng)建一個(gè)迭代器,生成值func(*item),其中item來(lái)自iterable,只有當(dāng)iterable生成的項(xiàng)適用于這種調(diào)用函數(shù)的方式時(shí),此函數(shù)才有效。
1 def starmap(function, iterable):
2 # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
3 for args in iterable:
4 yield function(*args)
takewhile(predicate [, iterable]):
創(chuàng)建一個(gè)迭代器,生成iterable中predicate(item)為T(mén)rue的項(xiàng),只要predicate計(jì)算為False,迭代就會(huì)立即停止。
1 def takewhile(predicate, iterable):
2 # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
3 for x in iterable:
4 if predicate(x):
5 yield x
6 else:
7 break
tee(iterable [, n]):
從iterable創(chuàng)建n個(gè)獨(dú)立的迭代器,創(chuàng)建的迭代器以n元組的形式返回,n的默認(rèn)值為2,此函數(shù)適用于任何可迭代的對(duì)象,但是,為了克隆原始迭代器,生成的項(xiàng)會(huì)被緩存,并在所有新創(chuàng)建的迭代器中使用,一定要注意,不要在調(diào)用tee()之后使用原始迭代器iterable,否則緩存機(jī)制可能無(wú)法正確工作。
def tee(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = next(it) # fetch a new value and
for d in deques: # load it to all the deques
d.append(newval)
yield mydeque.popleft()
return tuple(gen(d) for d in deques)
#Once tee() has made a split, the original iterable should not be used anywhere else; otherwise,
the iterable could get advanced without the tee objects being informed.
#This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored).
In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門(mén)控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書(shū)考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開(kāi)啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03