
Python:itertools模塊
itertools模塊包含創(chuàng)建有效迭代器的函數(shù),可以用各種方式對數(shù)據(jù)進(jìn)行循環(huán)操作,此模塊中的所有函數(shù)返回的迭代器都可以與for循環(huán)語句以及其他包含迭代器(如生成器和生成器表達(dá)式)的函數(shù)聯(lián)合使用。
chain(iter1, iter2, ..., iterN):
給出一組迭代器(iter1, iter2, ..., iterN),此函數(shù)創(chuàng)建一個新迭代器來將所有的迭代器鏈接起來,返回的迭代器從iter1開始生成項(xiàng),知道iter1被用完,然后從iter2生成項(xiàng),這一過程會持續(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òu)造函數(shù),其中的iterables是一個迭代變量,生成迭代序列,此操作的結(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)建一個迭代器,返回iterable中所有長度為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)建一個迭代器,生成從n開始的連續(xù)整數(shù),如果忽略n,則從0開始計(jì)算(注意:此迭代器不支持長整數(shù)),如果超出了sys.maxint,計(jì)數(shù)器將溢出并繼續(xù)從-sys.maxint-1開始計(jì)算。
cycle(iterable):
創(chuàng)建一個迭代器,對iterable中的元素反復(fù)執(zhí)行循環(huán)操作,內(nèi)部會生成iterable中的元素的一個副本,此副本用于返回循環(huán)中的重復(fù)項(xiàng)。
dropwhile(predicate, iterable):
創(chuàng)建一個迭代器,只要函數(shù)predicate(item)為True,就丟棄iterable中的項(xiàng),如果predicate返回False,就會生成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)建一個迭代器,對iterable生成的連續(xù)項(xiàng)進(jìn)行分組,在分組過程中會查找重復(fù)項(xiàng)。
如果iterable在多次連續(xù)迭代中生成了同一項(xiàng),則會定義一個組,如果將此函數(shù)應(yīng)用一個分類列表,那么分組將定義該列表中的所有唯一項(xiàng),key(如果已提供)是一個函數(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)建一個迭代器,僅生成iterable中predicate(item)為True的項(xiàng),如果predicate為None,將返回iterable中所有計(jì)算為True的項(xiàng)。
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
ifilterfalse(predicate, iterable):
創(chuàng)建一個迭代器,僅生成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)建一個迭代器,生成項(xiàng)function(i1, i2, ..., iN),其中i1,i2...iN分別來自迭代器iter1,iter2 ... iterN,如果function為None,則返回(i1, i2, ..., iN)形式的元組,只要提供的一個迭代器不再生成值,迭代就會停止。
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)建一個迭代器,生成項(xiàng)的方式類似于切片返回值: iterable[start : stop : step],將跳過前start個項(xiàng),迭代在stop所指定的位置停止,step指定用于跳過項(xiàng)的步幅。與切片不同,負(fù)值不會用于任何start,stop和step,如果省略了start,迭代將從0開始,如果省略了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)建一個迭代器,生成元組(i1, i2, ... iN),其中i1,i2 ... iN 分別來自迭代器iter1,iter2 ... iterN,只要提供的某個迭代器不再生成值,迭代就會停止,此函數(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()相同,但是迭代過程會持續(xù)到所有輸入迭代變量iter1,iter2等都耗盡為止,如果沒有使用fillvalue關(guān)鍵字參數(shù)指定不同的值,則使用None來填充已經(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)建一個迭代器,返回iterable中所有長度為r的項(xiàng)目序列,如果省略了r,那么序列的長度與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)建一個迭代器,生成表示item1,item2等中的項(xiàng)目的笛卡爾積的元組,repeat是一個關(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)建一個迭代器,重復(fù)生成object,times(如果已提供)指定重復(fù)計(jì)數(shù),如果未提供times,將無止盡返回該對象。
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)建一個迭代器,生成值func(*item),其中item來自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)建一個迭代器,生成iterable中predicate(item)為True的項(xiàng),只要predicate計(jì)算為False,迭代就會立即停止。
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個獨(dú)立的迭代器,創(chuàng)建的迭代器以n元組的形式返回,n的默認(rèn)值為2,此函數(shù)適用于任何可迭代的對象,但是,為了克隆原始迭代器,生成的項(xiàng)會被緩存,并在所有新創(chuàng)建的迭代器中使用,一定要注意,不要在調(diào)用tee()之后使用原始迭代器iterable,否則緩存機(jī)制可能無法正確工作。
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ù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
訓(xùn)練與驗(yàn)證損失驟升:機(jī)器學(xué)習(xí)訓(xùn)練中的異常診斷與解決方案 在機(jī)器學(xué)習(xí)模型訓(xùn)練過程中,“損失曲線” 是反映模型學(xué)習(xí)狀態(tài)的核心指 ...
2025-09-19解析 DataHub 與 Kafka:數(shù)據(jù)生態(tài)中兩類核心工具的差異與協(xié)同 在數(shù)字化轉(zhuǎn)型加速的今天,企業(yè)對數(shù)據(jù)的需求已從 “存儲” 轉(zhuǎn)向 “ ...
2025-09-19CDA 數(shù)據(jù)分析師:讓統(tǒng)計(jì)基本概念成為業(yè)務(wù)決策的底層邏輯 統(tǒng)計(jì)基本概念是商業(yè)數(shù)據(jù)分析的 “基礎(chǔ)語言”—— 從描述數(shù)據(jù)分布的 “均 ...
2025-09-19CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-19SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價(jià)值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時(shí),“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(shí)(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價(jià)值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點(diǎn)數(shù)據(jù)時(shí)的科學(xué)計(jì)數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價(jià)值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營問題、提升執(zhí)行效率的核心手段,其價(jià)值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11