Python 推导,内含,迭代器
生活随笔
收集整理的這篇文章主要介紹了
Python 推导,内含,迭代器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Python語法–推導(dǎo)或內(nèi)含
- list comprehension操作可以將一個序列類型的數(shù)據(jù)集推導(dǎo)出另一個序列類型的數(shù)據(jù)集:
- 以上情況同如下循環(huán)
- 具體案例如下:
推導(dǎo)+邏輯處理
- 具體案例如下
python中迭代器
- 迭代器是Python中一個數(shù)據(jù)量對象的容器,當(dāng)使用時候每次都從其中取出一個,直到取完
自定義迭代器
- 只要定義一個實現(xiàn)迭代器協(xié)議的方法類即可,主要協(xié)議方法與入學(xué)兩個
- 自定義迭代器代碼如下:
內(nèi)置迭代器工具
- Python中內(nèi)建了一個用于產(chǎn)生迭代器的函數(shù)iter(),另外一個標(biāo)準(zhǔn)庫的itertools模塊還有豐富的迭代器工具:
- 內(nèi)置迭代器工具實例:
itertools模塊中常用工具函數(shù)
import itertools## 迭代器工具類 ## 從1 開始,每此以3 為步迭代 def countTest():for i in itertools.count(1, 3):print(i)if i >= 10:break##無線循環(huán)迭代 def cycleTest():for i in itertools.cycle([1, 2, 3]):print(i)## 循環(huán)迭代 輸出: [2, 2, 2] def repeatTest():print(list(itertools.repeat(2, 3)))##chain(p,q,...)鏈接迭代,將p,q連接起來迭代輸出:[1, 2, 3, 4, 5, 6] def chainTest():print(list(itertools.chain([1, 2, 3], [4, 5, 6])))## compress(data,selectors) 根據(jù)selectors中的值選擇迭代data序列中的值 輸出: [1, 3] def compressTest():print(list(itertools.compress([1, 2, 3, 4], [1, None, True, False])))## dropwhile(pred,seq) 當(dāng)pred對序列元素處理結(jié)果為False時候開始迭代seq后所有的值 輸出:[1, 2, 10, 11] def dropwhileTest():print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## filterfalse(pred,seq) 當(dāng)pred處理為假的元素 輸出:[1, 2] def filterfalseTest():print(list(itertools.filterfalse(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## takewhile 與dropwhile相反 當(dāng)pred對序列元素處理結(jié)果為True時候開始迭代seq后所有的值 輸出:[8, 9] def takewhileTest():print(list(itertools.takewhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))## tee(it, n) 將it重復(fù)n次進(jìn)行迭代 def teeTest():for its in itertools.tee([0, 1], 2):for it in its:print(it)## zip_longest(p,q,...) 按每個序列中對應(yīng)位置元素組合成新的元素進(jìn)行迭代 def zip_longestTest():for i in itertools.zip_longest([1, 2, 3, 8], [3, 4, 5, 76], (0, 2, 3, 4)):print(i)## product(p,q,...[,n]) 迭代排列中出現(xiàn)元素的全排列 def productTest():for i in itertools.product([1, 2, 3, 8], [3, 4, 5, 76]):print(i)## permutations(p, q) 求p迭代序列中q個元素的全排列 def permutationsTest():print(list(itertools.permutations([1, 2, 3, 4], 4)))print(list(itertools.permutations('ASBD', 4)))## combinations(p, r)迭代序列中r個元素的組合 def combinationsTest():print(list(itertools.combinations('abc', 2)))print(list(itertools.combinations([1, 2, 3], 2)))if __name__ == '__main__':combinationsTest()總結(jié)
以上是生活随笔為你收集整理的Python 推导,内含,迭代器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线上问题排查流程
- 下一篇: python中的max_row_Open