itertools模塊:循環器函數
一,無窮循環器:count,cycle,repeat工具
(1)count(5,3) #從5開始的整數循環器,每次增長3,即:5,8,11,14,17... from itertools import * import time a = count(5,3) for i in a: print(i) time.sleep(1) 輸出結果爲: 5 8 11 14 17 20 23 26
(2)cycle('zxy') #重複元素x y z x y z x y z... from itertools import * import time s = cycle('xyz') for i in s: print(i) time.sleep(1) 輸出結果爲: x y z x y z x y z
repeat() #重複元素 例1: from itertools import * import time s = repeat(3.14) #無限重複元素 for i in s: print(i) time.sleep(1) 輸出結果爲: 3.14 3.14 3.14 3.14 3.14 3.14 例2: from itertools import * import time s = repeat(3,5) #重複元素3,共5次 for i in s: print(i) time.sleep(1) 輸出結果爲: 3 3 3 3 3
二,函數式工具:starmap,takewhile,dropwhilespa
(1)starmap() #跟map相似 from itertools import * s = starmap(pow,[(1,1),(2,2),(3,3)]) #pow()求指數1**1,2**2,3**3 for i in s: print(i) 輸出結果爲: 1 4 27 (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) 輸出結果爲: 1 2 3 4 (3)dropwhile() #與takewhile相反。 s2 = dropwhile(lambda x: x < 5, [1,2,3,4,5,6,7]) for i in s2: print(i) 輸出結果爲: 5 6 7