Python模組:itertools,pythonitertools

來源:互聯網
上載者:User

Python模組:itertools,pythonitertools

itertools模組:迴圈器

 

一,無窮迴圈器:count,cycle,repeat

(1)count(5,3)   #從5開始的整數迴圈器,每次增加3,即:5,8,11,14,17...from itertools import *import timea = count(5,3)for i in a:    print(i)    time.sleep(1)輸出結果為:58111417202326
(2)cycle('zxy')  #重複元素x y z x y z x y z... from itertools import *import times = cycle('xyz')for i in s:    print(i)    time.sleep(1)輸出結果為:xyzxyzxyz
repeat()   #重複元素例1:from itertools import *import times = repeat(3.14)  #無限重複元素for i in s:    print(i)    time.sleep(1)輸出結果為:3.143.143.143.143.143.14例2:from itertools import *import times = repeat(3,5)   #重複元素3,共5次for i in s:    print(i)    time.sleep(1)輸出結果為:33333

 

二,函數式工具:starmap,takewhile,dropwhile

(1)starmap()    #跟map類似from itertools import *s = starmap(pow,[(1,1),(2,2),(3,3)])  #pow()求指數1**1,2**2,3**3for i in s:    print(i)輸出結果為:1427(2)takewhile()   #當函數返回True時,收集元素到迴圈器。一旦函數返回False,則停止。from itertools import *s1 = takewhile(lambda x: x < 5, [1,2,3,4,5,6,7])for i in s1:    print(i)輸出結果為:1234(3)dropwhile()   #與takewhile相反。s2 = dropwhile(lambda x: x < 5, [1,2,3,4,5,6,7])for i in s2:    print(i)輸出結果為:567

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.