python迭代器以及itertools模組,pythonitertools

來源:互聯網
上載者:User

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')]

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.