python模組分析之itertools
前言
itertools模組是python內建的迭代器模組,定義了可生成多種迭代器的函式,用來代替可迭代物件的遍歷等操作,節約記憶體。
迭代器函式的型別
無限迭代器:包括count、cycle、repeat,用於生成無限序列的迭代器;
有限迭代器:接收一個或多個序列作為引數,進行組合、分組和過濾等;
組合生成器:多個序列的排列、組合等
無限迭代器
count
count本身是一個迭代器,實現了__iter__和__next__方法,用來生成無限的數字序列。
# 引數: start=0:迭代的起點 step=1:步長 for i in count(): print(i) if i == 1000: break
accumulate
accumulate對一個序列的資料進行積累。
# 引數
iterable:可迭代物件
func:指定規則
from itertools import accumulate
print(list(accumulate([1,2,3,4], func=lambda x,y:x + y))) # 這是預設的規則
# 結果
[1, 3, 6, 10]
cycle
迭代器,對迭代物件進行無限的重複迭代。
# 引數: iterable:可迭代物件 from itertools import cycle j = 0 for i in cycle(range(2)): j += 1 print(i) # 結果:0 1 0 1 0 1 if j == 6: break
repeat
repeat用於反覆生成相同的物件,注意它們其實指向的是同一個物件,只是生成了眾多的引用。
# 引數
p_object:任何物件;
times:生成的次數,預設是無限的;
from itertools import repeat
for i in repeat([1,2,3], times=2):
print(i)
有限迭代器
迭代器拼接chain
chain可將多個迭代器拼接返回新的迭代器。
# 引數為眾多的可迭代物件 from itertools import chain x = list(chain(range(5),range(4))) print(x) # [0, 1, 2, 3, 4, 0, 1, 2, 3]
資料篩選compress
compress 可用於對資料進行篩選,當 selectors 的某個元素為 true 時,則保留 data 對應位置的元素,否則去除,data位置不夠預設為false。
# 引數
data:待篩選資料
selectors:篩選規則
from itertools import compress
x = list(compress({'name':'','age':''}, [0,1]))
print(x) # ['age']
資料分組groupby
groupby迭代器對可迭代物件的元素按指定的規則分組。
# 引數
data:需要分組的可迭代物件
key:分組規則
from itertools import groupby
x = groupby(['name','age'], key=len)
print([(x, list(y)) for x, y in x]) # [(4, ['name']), (3, ['age'])]
資料過濾
- dropwhile:
# 引數
predicate:過濾函式
iterable:迭代物件
from itertools import dropwhile
print(list(dropwhile(lambda x:x<1,[False,False,1,2,3]))) # [1, 2, 3]
對於 iterable 中的元素,如果 predicate(item) 為 true,則丟棄該元素,否則返回該項及所有後續項;如果所有的元素都返回False,那麼全部保留。
- takewhile
# 引數
predicate:過濾函式
iterable:迭代物件
takewhile和dropwhile迭代器剛好相反,對於 iterable 中的元素,如果 predicate(item) 為 true,則保留該元素,只要 predicate(item) 為 false,則立即停止迭代,返回被迭代過的保留的元素。
- filterfalse
from itertools import filterfalse
print(list(filterfalse(None, ['', 1, []])))
filterfalse的過濾條件和內建函式filter剛好相反,保留返回false而丟棄返回True的元素。
ifilter:在py2中存在,py3已去除,使用內建函式filter替代。
starmap
starmap的功能和map函式非常相似,不過starmap的可迭代物件引數必須是元組序列。
from itertools import starmap
print(list(starmap(lambda x:x, [[1,],[3,]])))
資料切片
- islice
# 引數
iterable:可迭代物件,支援字典和集合的切片,但返回的結果未知。
start: 起點
stop:終點
step:步長
from itertools import islice
print(list(islice([5,4,3,4,5,6],1,3,1)))
迭代器重複建立tee
from itertools import tee, takewhile
for t in tee([1,2,3], 4):
print(t)
print(id(t))
tee建立的多個迭代器都是相互獨立的物件,預設建立兩個獨立的迭代器。
打包迭代器
izip:py2中存在,和py3的內建函式zip的功能相同。
zip_longest
# 引數
*iter:多個可迭代物件
fillvalue:缺失值的預設
from itertools import zip_longest
for z in zip_longest([1,2,3],[1,2],fillvalue=10):
print(z)
zip_longest和zip的功能相似,但是zip_longest會將所有的元素迭代完成,不夠的用預設值替代。
組合生成器
組合生成器用來求多個序列的排列組合。
product:求多個可迭代物件的笛卡爾積;
permutations:生成元素不可重複的排列;
combinations:生成元素不可重複的組合;
combinations_with_replacement:生成元素可重複的組合;
總結
一般來說,如果能夠用迭代器的場景儘量使用迭代器,可以極大改善記憶體使用狀況;
本模組比較常用的迭代器為:chain,dropwhilezip_longest.