10個(gè)Python Itertools方法助你事半功倍
用更短的代碼實(shí)現(xiàn)相同的功能,使用10個(gè)Python Itertools方法讓代碼更簡潔。
簡介
Python的編程優(yōu)勢在于它的簡潔性。這不僅是因?yàn)镻ython語法優(yōu)雅,還因?yàn)樗性S多精心設(shè)計(jì)的內(nèi)置模塊,可以幫助開發(fā)者高效地實(shí)現(xiàn)常用功能。
itertools
模塊就是一個(gè)很好的例子,它為開發(fā)者提供了許多強(qiáng)大的工具,可以用更短的代碼來操作Python的可迭代對(duì)象,幫助開發(fā)者事半功倍地完成任務(wù)。
1. itertools.product():避免嵌套循環(huán)的巧妙方式
當(dāng)程序變得越來越復(fù)雜時(shí),可能需要編寫嵌套循環(huán)。與此同時(shí),Python代碼將變得丑陋和難以閱讀:
list_a = [1, 2020, 70] list_b = [2, 4, 7, 2000] list_c = [3, 70, 7] for a in list_a: for b in list_b: for c in list_c: if a + b + c == 2077: print(a, b, c) # 70 2000 7
如何改進(jìn)上述代碼,使其具有Python風(fēng)格?
可以使用itertools.product()
函數(shù):
from itertools import product list_a = [1, 2020, 70] list_b = [2, 4, 7, 2000] list_c = [3, 70, 7] for a, b, c in product(list_a, list_b, list_c): if a + b + c == 2077: print(a, b, c) # 70 2000 7
如上所示,它返回輸入可迭代對(duì)象的笛卡爾積,幫助將3個(gè)嵌套的for
循環(huán)合并為一個(gè)。
2. itertools.compress():過濾數(shù)據(jù)的便捷方式
可以通過一個(gè)或多個(gè)循環(huán)來過濾列表中的項(xiàng)目。
但有時(shí)候,可能不需要編寫任何循環(huán),而是使用函數(shù)itertools.compress()
。
itertools.compress()
函數(shù)返回一個(gè)迭代器,該迭代器根據(jù)對(duì)應(yīng)的布爾掩碼值對(duì)可迭代對(duì)象進(jìn)行過濾。
例如,以下代碼使用itertools.compress()
函數(shù)選擇真正的數(shù)據(jù):
import itertools leaders = ['Yang', 'Elon', 'Tim', 'Tom', 'Mark'] selector = [1, 1, 0, 0, 0] print(list(itertools.compress(leaders, selector))) # ['Yang', 'Elon']
第二個(gè)參數(shù)selector
作為一個(gè)掩碼,也可以定義為以下形式:
selector = [True, True, False, False, False]
3. itertools.groupby():對(duì)可迭代對(duì)象進(jìn)行分組
itertools.groupby()
函數(shù)是將可迭代對(duì)象中相鄰的重復(fù)元素進(jìn)行分組的一種便捷方式。
例如,可以對(duì)一個(gè)長字符串進(jìn)行如下分組:
from itertools import groupby for key, group in groupby('YAaANNGGG'): print(key, list(group)) # Y ['Y'] # A ['A'] # a ['a'] # A ['A'] # N ['N', 'N'] # G ['G', 'G', 'G']
此外,還可以利用它的第二個(gè)參數(shù)來告訴groupby()
函數(shù)如何判斷兩個(gè)元素是否相同:
from itertools import groupby for key, group in groupby('YAaANNGGG', lambda x: x.upper()): print(key, list(group)) # Y ['Y'] # A ['A', 'a', 'A'] # N ['N', 'N'] # G ['G', 'G', 'G']
4. itertools.combinations():獲取可迭代對(duì)象中給定長度的所有組合
對(duì)于初學(xué)者來說,編寫一個(gè)正確的函數(shù)來獲取列表的所有可能組合可能需要一些時(shí)間。
實(shí)際上,如果使用itertools.combinations()
函數(shù),可以很容易地實(shí)現(xiàn):
import itertools author = ['Y', 'a', 'n', 'g'] result = itertools.combinations(author, 2) for x in result: print(x) # ('Y', 'a') # ('Y', 'n') # ('Y', 'g') # ('a', 'n') # ('a', 'g') # ('n', 'g')
如上述程序所示,itertools.combinations()
函數(shù)有兩個(gè)參數(shù),一個(gè)是原始可迭代對(duì)象,另一個(gè)是函數(shù)生成的子序列的長度。
5. itertools.permutations(): 獲取可迭代對(duì)象中給定長度的所有排列
既然有一個(gè)函數(shù)可以獲取所有組合,當(dāng)然還有另一個(gè)名為itertools.permutations
的函數(shù)可以獲取所有可能的排列:
import itertools author = ['Y', 'a', 'n', 'g'] result = itertools.permutations(author, 2) for x in result: print(x) # ('Y', 'a') # ('Y', 'n') # ('Y', 'g') # ('a', 'Y') # ('a', 'n') # ('a', 'g') # ('n', 'Y') # ('n', 'a') # ('n', 'g') # ('g', 'Y') # ('g', 'a') # ('g', 'n')
如上所示,itertools.permutations()
函數(shù)的使用方式與itertools.combinations()
函數(shù)類似。唯一的區(qū)別在于它們的結(jié)果。
6. itertools.accumulate():從可迭代對(duì)象生成累積項(xiàng)
基于可迭代對(duì)象獲取一系列累積值是一種常見的需求。借助itertools.accumulate()
函數(shù)的幫助,不需要編寫任何循環(huán)就能實(shí)現(xiàn)。
import itertools import operator nums = [1, 2, 3, 4, 5] print(list(itertools.accumulate(nums, operator.mul))) # [1, 2, 6, 24, 120]
如果不想使用operator.mul
,上述程序與以下程序相同:
import itertools nums = [1, 2, 3, 4, 5] print(list(itertools.accumulate(nums, lambda a, b: a * b))) # [1, 2, 6, 24, 120]
7. itertools.repeat(), itertools.cycle(), itertools.count():創(chuàng)建無限迭代器
在某些情況下,開發(fā)者需要獲得一個(gè)無限迭代器。有3個(gè)函數(shù)可以幫助實(shí)現(xiàn):
7.1 itertools.repeat():重復(fù)生成相同的項(xiàng)目
例如,可以按以下方式獲取三個(gè)相同的“Yang”:
import itertools print(list(itertools.repeat('Yang', 3))) # ['Yang', 'Yang', 'Yang']
7.2 itertools.cycle():通過循環(huán)獲取無限迭代器
itertools.cycle
函數(shù)在中斷循環(huán)之前不會(huì)停止:
import itertools count = 0 for c in itertools.cycle('Yang'): if count >= 12: break else: print(c, end=',') count += 1 # Y,a,n,g,Y,a,n,g,Y,a,n,g,
7.3 itertools.count():生成一個(gè)無限的數(shù)字序列
如果需要的只是數(shù)字,可以使用itertools.count
函數(shù):
import itertools for i in itertools.count(0, 2): if i == 20: break else: print(i, end=" ") # 0 2 4 6 8 10 12 14 16 18
如上所示,它的第一個(gè)參數(shù)是起始數(shù)字,第二個(gè)參數(shù)是步長。
8. itertools.pairwise():輕松獲取成對(duì)的元組
自Python 3.10以來,itertools
模塊新增了一個(gè)名為pairwise
的新函數(shù)。它是一個(gè)簡潔的工具,可以從可迭代對(duì)象生成連續(xù)重疊的成對(duì)元素。
import itertools letters = ['a', 'b', 'c', 'd', 'e'] result = itertools.pairwise(letters) print(list(result)) # [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
9. itertools.takewhile():以不同的方式過濾元素
itertools.takewhile()
返回一個(gè)迭代器,只要給定的謂詞函數(shù)評(píng)估為True
,該迭代器就會(huì)生成可迭代對(duì)象中的元素。
import itertools nums = [1, 61, 7, 9, 2077] print(list(itertools.takewhile(lambda x: x < 100, nums))) # [1, 61, 7, 9]
此函數(shù)與內(nèi)置的filter()
函數(shù)不同。
filter
函數(shù)將遍歷整個(gè)列表:
nums = [1, 61, 7, 9, 2077] print(list(filter(lambda x: x < 10, nums))) # [1, 7, 9]
然而,itertools.takewhile
函數(shù)會(huì)在評(píng)估函數(shù)為False
時(shí)停止:
import itertools nums = [1, 61, 7, 9, 2077] print(list(itertools.takewhile(lambda x: x < 10, nums))) # [1]
10. itertools.dropwhile():itertools.takewhile的反向操作
這個(gè)函數(shù)是上一個(gè)函數(shù)的逆操作。
itertools.takewhile()
函數(shù)在True
時(shí)返回可迭代對(duì)象中的元素,而itertools.dropwhile()
函數(shù)會(huì)在True
時(shí)刪除可迭代對(duì)象的元素,并返回剩余的元素。
import itertools nums = [1, 61, 7, 9, 2077] print(list(itertools.dropwhile(lambda x: x < 100, nums))) # [2077]
到此這篇關(guān)于Python中itertools高效迭代工具的文章就介紹到這了,更多相關(guān)Python itertools內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
numpy.ndarray.flatten()函數(shù)的具體使用
本文主要介紹了numpy.ndarray.flatten()函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03Python關(guān)于sys.argv[]的用法及說明
sys.argv[]是Python中用于從程序外部獲取參數(shù)的列表,參數(shù)索引從0開始,0索引代表腳本名稱本身,后續(xù)索引代表傳遞給腳本的參數(shù),通過指定索引可以獲取特定的參數(shù),如sys.argv[1]獲取第一個(gè)傳入?yún)?shù),當(dāng)傳入多個(gè)參數(shù)時(shí),可以通過切片或循環(huán)獲取全部參數(shù)2024-09-09Python文件基本操作open函數(shù)應(yīng)用與示例詳解
這篇文章主要為大家介紹了Python文件基本操作open函數(shù)應(yīng)用與示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12python實(shí)現(xiàn)BP神經(jīng)網(wǎng)絡(luò)回歸預(yù)測模型
這篇文章主要介紹了python實(shí)現(xiàn)BP神經(jīng)網(wǎng)絡(luò)回歸預(yù)測模型,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08用Python和WordCloud繪制詞云的實(shí)現(xiàn)方法(內(nèi)附讓字體清晰的秘笈)
這篇文章主要介紹了用Python和WordCloud繪制詞云的實(shí)現(xiàn)方法(內(nèi)附讓字體清晰的秘笈),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01Python 編碼處理-str與Unicode的區(qū)別
本文主要介紹Python 編碼處理的問題,這里整理了相關(guān)資料,并詳細(xì)說明如何處理編碼問題,有需要的小伙伴可以參考下2016-09-09Django實(shí)現(xiàn)的自定義訪問日志模塊示例
這篇文章主要介紹了Django實(shí)現(xiàn)的自定義訪問日志模塊,結(jié)合具體實(shí)例形式分析了Django針對(duì)日志的相關(guān)操作技巧,需要的朋友可以參考下2017-06-06python讀取dicom圖像示例(SimpleITK和dicom包實(shí)現(xiàn))
今天小編就為大家分享一篇python讀取dicom圖像示例(SimpleITK和dicom包實(shí)現(xiàn)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01