python迭代器模塊itertools常用的方法
前言
itertools是python中內(nèi)置的一種高效的生成各種迭代器或者是類的模塊,這些函數(shù)的返回值為一個(gè)迭代器,經(jīng)常被用在for循環(huán)中,當(dāng)然,也可直接使用next()方法取值,今天就來說說itertools中的常用方法.
itertools按照迭代器的功能可分為三類:
- 無限迭代器: 生成一個(gè)無限序列,比如自然數(shù)序列 1, 2, 3, 4, …
- 有限迭代器: 接收一個(gè)或多個(gè)序列(sequence)作為參數(shù),進(jìn)行組合、分組和過濾等;
- 組合迭代器: 序列的排列、組合,求序列的笛卡兒積等
1.無限迭代器
itertools.count(start=0, step=1)
創(chuàng)建一個(gè)迭代器,生成從n開始的連續(xù)整數(shù),如果忽略n,則從0開始計(jì)算(注意:此迭代器不支持長(zhǎng)整數(shù)),如果超出了sys.maxint,計(jì)數(shù)器將溢出并繼續(xù)從-sys.maxint-1開始計(jì)算
- start: 起始值,默認(rèn)為0
- step: 步長(zhǎng),默認(rèn)為1
import itertools a = itertools.count() for x in a: if x > 5: break print(x)
輸出:
1
2
3
4
5
6
b = itertools.count(2,3) for x in b: if x > 10: break print(x)
輸出:
2
5
8
itertools.cycle(iterable)
創(chuàng)建一個(gè)迭代器,對(duì)iterable中的元素反復(fù)執(zhí)行循環(huán)操作,內(nèi)部會(huì)生成iterable中的元素的一個(gè)副本,此副本用于返回循環(huán)中的重復(fù)項(xiàng)
iterable: 可迭代對(duì)象,可以為一個(gè)列表、字符串、元組等
import itertools a = ['a','b','c'] i = 0 for x in itertools.cycle(a): i = i +1 if i > 5: break print(i,x)
輸出:
1,'a'
2,'b'
3,'c'
4,'a'
5,'b'
itertools.repeat(object[, times])
創(chuàng)建一個(gè)迭代器,重復(fù)生成object,times(如果已提供)指定重復(fù)計(jì)數(shù),如果未提供times,將無止盡返回該對(duì)象
- object: 需要重復(fù)的對(duì)象,對(duì)象是個(gè)整體
- times: 重復(fù)次數(shù)
import itertools for x in itertools.repeat([1,2,3],3): print(x)
輸出:
[1,2,3]
[1,2,3]
[1,2,3]
2.有限迭代器
itertools.chain(iterable1, iterable2, …)
將多個(gè)迭代器作為參數(shù), 但只返回單個(gè)迭代器, 它產(chǎn)生所有參數(shù)迭代器的內(nèi)容, 就好像他們是來自于一個(gè)單一的序列
參數(shù)為多個(gè)可迭代對(duì)象,就好像被鏈條銜接起來了一樣
import itertools for x in itertools.chain([1,2,3],'abc'): print(x)
輸出:
1
2
3
'a'
'b'
'c'
for x in itertools.chain([1,2,3],['a','b','c']): print(x)
輸出:
1
2
3
'a'
'b'
'c'
itertools.chain.from_iterable(iterable)
接收一個(gè)可迭代對(duì)象作為參數(shù),返回一個(gè)迭代器
from itertools import chain a = [['first','second','thrid'],['a','b','c']] b = [[1,2,3],[4,5,6]] for x in range(len(a)): list(chain.from_iterable(zip(a[x],b[x])))
輸出:
['first', 1, 'second', 2, 'thrid', 3]
['a', 4, 'b', 5, 'c', 6]
itertools.compress(data, selectors)
#可用于對(duì)數(shù)據(jù)進(jìn)行篩選,當(dāng) selectors 的某個(gè)元素為 true 時(shí),則保留 data 對(duì)應(yīng)位置的元素,否則去除
#data: 待篩選數(shù)據(jù)
#selectors: 當(dāng)為真時(shí),保留data對(duì)應(yīng)位的數(shù)據(jù),為假或?yàn)榭諘r(shí)則去除
from itertools import compress for x in compress(['a','b','c','d'],[1,0,2]): print(x)
輸出:
'a'
'c'
# 2 也為真,'d'對(duì)應(yīng)值為空算假
itertools.dropwhile(predicate, iterable)
創(chuàng)建一個(gè)迭代器,只要函數(shù)predicate(item)為True,就丟棄iterable中的項(xiàng),如果predicate返回False,就會(huì)生成iterable中的項(xiàng)和所有后續(xù)項(xiàng),即第一個(gè)不滿足條件的項(xiàng)及它后面所有的項(xiàng)都返回
- predicate: 函數(shù)
- iterable: 可迭代對(duì)象
from itertools import dropwhile list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
輸出:
[6,2,1]
#從6開始不符合x < 5 條件,所以6及6后面所有的項(xiàng)都需要返回
itertools.takewhile(predicate, iterable)
創(chuàng)建一個(gè)迭代器,如果predicate返回False,立即停止迭代
from itertools import takewhile list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
輸出:
[1,3]
itertools.ifilter(predicate, iterable)
創(chuàng)建一個(gè)迭代器,僅生成iterable中predicate(item)為True的項(xiàng),如果predicate為None,將返回iterable中所有計(jì)算為True的項(xiàng)
- predicate: 函數(shù)
- iterable: 可迭代對(duì)象
from itertools import ifilter list(ifilter(lambda x: x < 5, [1, 3, 6, 2, 1]))
輸出:
[1,3,2,1]
itertools.ifilterfalse(predicate, iterable)
創(chuàng)建一個(gè)迭代器,僅生成iterable中predicate(item)為False的項(xiàng),如果predicate為None,將返回iterable中所有計(jì)算False的項(xiàng),該函數(shù)正好跟ifilter相反
- predicate: 函數(shù)
- iterable: 可迭代對(duì)象
from itertools import ifilterfalse list(ifilterfalse(lambda x: x < 5, [1, 3, 6, 2, 1]))
輸出:
[6]
itertools.groupby(iterable[, key])
返回一個(gè)產(chǎn)生按照key進(jìn)行分組后的值集合的迭代器
- iterable:可迭代對(duì)象
- key: 一個(gè)函數(shù),該函數(shù)的返回值做為分組的標(biāo)準(zhǔn)
from itertools import groupby a = ['aa', 'ab', 'abc', 'bcd', 'abcde'] for i, k in groupby(a, len): print (i, list(k))
輸出:
2,['aa', 'ab']
3,['abc', 'bcd']
5,['abcde']
itertools.islice(iterable, stop)
iterable 是可迭代對(duì)象,start 是開始索引,默認(rèn)為0,stop 是結(jié)束索引,step 是步長(zhǎng),默認(rèn)為1,start 和 step 可選
from itertools import islice,count list(islice([10, 6, 2, 8, 1, 3, 9], 5))
輸出:
[[10, 6, 2, 8, 1]
list(islice(count(), 3, 10 ,2))
輸出:
[3,5,7,9]
#這里的count()為文章第一個(gè)函數(shù),用來產(chǎn)生無限序列
itertools.imap(func, iter1, iter2, iter3, …)
imap(func, iter1, iter2, iter3, …)
返回一個(gè)迭代器, 它是調(diào)用了一個(gè)其值在輸入迭代器上的函數(shù), 返回結(jié)果. 它類似于內(nèi)置函數(shù) map() , 只是前者在任意輸入迭代器結(jié)束后就停止(而不是插入None值來補(bǔ)全所有的輸入)
注意: 該函數(shù)在python3.x中已不存在,可直接使用map
from itertools import imap list(imap(pow, [2, 3, 10], [4, 2, 3]))
輸出:
[16, 9, 1000]
#pow函數(shù) 求指數(shù)
itertools.izip(*iterables)
用于將多個(gè)可迭代對(duì)象對(duì)應(yīng)位置的元素作為一個(gè)元組,將所有元組『組成』一個(gè)迭代器,并返回
注意: 該函數(shù)在python3.x中已不存在,可直接使用zip
from itertools import izip for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']): print(item)
輸出:
(1, 'a')
(2, 'b')
(3, 'c')
*itertools.izip_longest(iterables, [fillvalue=None])
izip_longest 跟 izip 類似,但迭代過程會(huì)持續(xù)到所有可迭代對(duì)象的元素都被迭代完
注意: 該函數(shù)在python3.x中已不存在
from itertools import izip_longest for item in izip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e'],fillvalue='-'): print(item)
輸出:
(1, 'a')
(2, 'b')
(3, 'c')
('-','d')
('-','e')
3.組合迭代器
*itertools.product(iterables[, repeat])
創(chuàng)建一個(gè)迭代器,生成表示item1,item2等中的項(xiàng)目的笛卡爾積的元組,repeat是一個(gè)關(guān)鍵字參數(shù),指定重復(fù)生成序列的次數(shù)。
用來產(chǎn)生笛卡爾積
import itertools a = (1, 2, 3) b = ('A', 'B', 'C') c = itertools.product(a,b) for elem in c: print(elem)
輸出:
(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')
list(product((0,1), (0,1), (0,1)))
輸出:
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
list(product('ABC', repeat=2))
輸出:
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
itertools.product的簡(jiǎn)單使用:
from itertools import product # 迭代器 # test script for i j in product(range(10),range(10)) print(i,j) # 同理等于兩個(gè)for循環(huán)嵌套,只是這種寫法遠(yuǎn)行速度遍歷會(huì)快一些,時(shí)間復(fù)雜度減小。 for x in range(10): for y in range(10): print(x,y)
itertools.permutations(iterable[, r])
創(chuàng)建一個(gè)迭代器,返回iterable中所有長(zhǎng)度為r的項(xiàng)目序列,如果省略了r,那么序列的長(zhǎng)度與iterable中的項(xiàng)目數(shù)量相同: 返回p中任意取r個(gè)元素做排列的元組的迭代器
from itertools import permutations list(permutations('ABC', 2))
輸出:
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
itertools.combinations(iterable, r)
創(chuàng)建一個(gè)迭代器,返回iterable中所有長(zhǎng)度為r的子序列,返回的子序列中的項(xiàng)按輸入iterable中的順序排序 (不帶重復(fù))
from itertools import combinations list(combinations('ABC', 2))
輸出:
[('A', 'B'), ('A', 'C'), ('B', 'C')]
itertools.combinations_with_replacement(iterable, r)
創(chuàng)建一個(gè)迭代器,返回iterable中所有長(zhǎng)度為r的子序列,返回的子序列中的項(xiàng)按輸入iterable中的順序排序 (帶重復(fù))
from itertools import combinations_with_replacement list(combinations_with_replacement('ABC', 2))
輸出:
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
到此這篇關(guān)于python迭代器模塊itertools常用的方法的文章就介紹到這了,更多相關(guān)python itertools 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中itertools簡(jiǎn)介使用介紹
- Python中itertools模塊的使用教程詳解
- Python中itertools庫(kù)的四個(gè)函數(shù)介紹
- 淺析Python自帶性能強(qiáng)悍的標(biāo)準(zhǔn)庫(kù)itertools
- python中itertools模塊使用小結(jié)
- 關(guān)于Python 內(nèi)置庫(kù) itertools
- Python函數(shù)式編程中itertools模塊詳解
- Python編程itertools模塊處理可迭代集合相關(guān)函數(shù)
- 關(guān)于Python中 循環(huán)器 itertools的介紹
- 詳解python itertools功能
- python排列組合庫(kù)itertools的具體使用
相關(guān)文章
Pycharm編輯器功能之代碼折疊效果的實(shí)現(xiàn)代碼
這篇文章主要介紹了Pycharm編輯器功能之代碼折疊效果的實(shí)現(xiàn)代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10將Python項(xiàng)目打包成exe并附帶下載功能的操作流程
這篇文章主要為大家詳細(xì)介紹了將Python項(xiàng)目打包成exe并附帶下載功能的操作流程,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解下2023-12-12Python??序列化反序列化和異常處理的問題小結(jié)
這篇文章主要介紹了Python?序列化反序列化和異常處理,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12python數(shù)據(jù)寫入列表并導(dǎo)出折線圖
這篇文章主要介紹了python數(shù)據(jù)寫入列表并導(dǎo)出折線圖,文章以舉例展開對(duì)文章主題的介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-01-01使Python代碼流暢無縫連接的鏈?zhǔn)秸{(diào)用技巧
鏈?zhǔn)秸{(diào)用是一種編程風(fēng)格,它允許將多個(gè)方法調(diào)用連接在一起,形成一個(gè)連貫的操作鏈,在Python中,鏈?zhǔn)秸{(diào)用常常用于使代碼更簡(jiǎn)潔、易讀,尤其在處理數(shù)據(jù)處理和函數(shù)式編程中應(yīng)用廣泛2024-01-01使用 Python 處理3萬多條數(shù)據(jù)只要幾秒鐘
在工作中經(jīng)常遇到大量的數(shù)據(jù)需要整合、去重、按照特定格式導(dǎo)出等情況。這篇文章主要介紹了使用 Python 處理3萬多條數(shù)據(jù)只要幾秒鐘的相關(guān)知識(shí),需要的朋友可以參考下2020-01-01Python檢測(cè)一個(gè)對(duì)象是否為字符串類的方法
這篇文章主要介紹了Python檢測(cè)一個(gè)對(duì)象是否為字符串類的方法,即檢測(cè)是一個(gè)對(duì)象是否是字符串對(duì)象,本文還講解了一個(gè)有趣的判斷方法,需要的朋友可以參考下2015-05-05