python迭代器以及itertools模組,pythonitertools
迭代器
在python中,迭代器協議就是實現對象的__iter()方法和next()方法,其中前者返回對象本身,後者返回容器的下一個元素。實現了這兩個方法的對象就是可迭代對象。迭代器是有惰性的,只有在使用時才會產生,這就為處理大量資料提供了好處,不同一次性把所有資料寫入記憶體。下面自己寫了一個迭代器,可以看到使用for迴圈可以處理自己編寫的迭代器,實現了迭代器協議的對象,可以使用任何類似於for迴圈這樣的迭代器工具。但是,看下面的輸出,第二次輸出為空白,這是為什麼呢?我們在使用list時,可以多次輸出同一個對象,這和實現了自己實現了迭代器協議的對象有什麼區別?
1 class it(object): 2 def __init__(self, n): 3 self.a = 0 4 self.n = n 5 6 def __iter__(self): 7 return self 8 9 def next(self):10 if self.a < self.n:11 self.a += 112 return self.a13 else:14 raise StopIteration15 16 i=it(5)17 for j in i:18 print j,19 print ''20 print '------'21 for j in i:22 print j23 # 1 2 3 4 524 # ------
經過學習,得知,list等類型迭代器返回的是一個迭代器對象,不是返回了本身。那麼就寫了如下代碼進行測試,經過列印輸出可以看到,類TestIt的對象是可以反覆使用的。那麼又有一個問題了,沒有實現next()方法的對象,還是迭代器對象嗎?這是因為在使用it類時,是返回了迭代器對象的,把迭代的功能使用了it迭代器實現,也就是說相當於實現了迭代器協議。迭代器協議在python中很有用,python中有一個關於迭代器的模組itertools,下面我就學習一下itertools模組,看看有哪些驚喜!
1 class TestIt(object):2 def __init__(self, a):3 self.a = a4 5 def __iter__(self):6 return it(self.a)
itertools
無限迭代器
1 count(),接受兩個參數,第一個是開始的數字,第二個是步幅,預設從0開始,用法如下
1 import itertools as it2 3 c = it.count(10, 2)4 for i in c:5 if i > 20:6 break7 print i,8 # 10 12 14 16 18 20
2 cycle(),接受一個參數,該參數是迭代器對象(列表,字串等),會迴圈產生迭代器中的元素
1 c = it.cycle([1, 2, 3])2 i = 13 for j in c:4 if i > 7:5 break6 print j,7 i += 1
3 repeat(),接受兩個參數,用於產生第一個參數n次
1 for j in it.repeat([1, 2, 3], 4):2 print j
有限迭代器,選取感覺自己常用的介紹下
1 chain(),接受多個迭代器對象作為參數,並把它們串連起來chain('abc', [1, 2, 3])
2 compress(data, selectors), 根據後面的參數過濾前面的參數,兩個參數都需要是迭代器對象
3 dropwhile(pre, iterable),pre參數是一個函數,當pre(i)是Ture是,返回該項以及後面所有項
4 groupby(iterable[, keyfunc]),其中iterable 是一個可迭代對象,keyfunc 是分組函數,用於對 iterable 的連續項進行分組,如果不指定,則預設對 iterable 中的連續相同項進行分組,返回一個 (key, sub-iterator) 的迭代器。
5 ifilter(function or None, sequence),將 iterable 中 function(item) 為 True 的元素組成一個迭代器返回,如果 function 是 None,則返回 iterable 中所有計算為 True 的項
6 tee(iterable [,n]),tee 用於從 iterable 建立 n 個獨立的迭代器,以元組的形式返回,n 的預設值是 2。
1 for j in it.tee('abc', 4):2 print list(j)
組合產生器
1 permutations(iterable[, r]),用於產生一個排列,r是產生排列的元素長度,不指定則為預設長度
1 print list(it.permutations('abc'))2 print list(it.permutations('abc', 2))3 # [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]4 # [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
2 combinations(iterable, r), 求序列的組合,其中,r 指定產生組合的元素的長度,是必要參數
3 combinations_with_replacement(iterable, r),產生的組合包含自身元素
1 print list(it.combinations_with_replacement('abc', 2))2 # [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]