python排列組合庫(kù)itertools的具體使用
一、【說(shuō)在前面】
看到這篇文章的大兄弟您們好,我們經(jīng)常說(shuō)調(diào)包俠、CRUD仔,用來(lái)鄙視不會(huì)自己造輪子的工程師,不過(guò)筆者認(rèn)為python的精髓就是調(diào)庫(kù)。庫(kù)很快,自己寫(xiě)大概率更慢。調(diào)包俠也是有高低貴賤之分的,今天介紹一個(gè)特別好用的庫(kù)——itertools
這個(gè)庫(kù)會(huì)自動(dòng)產(chǎn)生一些諸如:排列、組合、笛卡爾積、多迭代器整合、zip等。更詳細(xì)可以看這個(gè)官網(wǎng)一手資料。
itertools — Functions creating iterators for efficient looping — Python 3.12.1 documentation
二、【正式介紹】
(1)無(wú)限循環(huán)迭代器
count(start[, step]):
count()
函數(shù)生成一個(gè)從 start
開(kāi)始的無(wú)限遞增的整數(shù)序列。如果提供了 step
參數(shù),則按照步長(zhǎng)遞增。
Arguments:
start
: 序列的起始值,默認(rèn)為 0。
step
: 序列的步長(zhǎng),默認(rèn)為 1。
Results:
生成一個(gè)無(wú)限遞增的整數(shù)序列。
Example:
from itertools import count # 從10開(kāi)始,步長(zhǎng)為2,不寫(xiě)默認(rèn)步長(zhǎng)為1 for i in count(10, 2): print(i) # 10,12,14,16……
cycle(iterable):
cycle()
函數(shù)接受一個(gè)可迭代對(duì)象,并無(wú)限循環(huán)輸出該可迭代對(duì)象的元素。
Arguments:
iterable
: 要循環(huán)的可迭代對(duì)象。
Results:
無(wú)限循環(huán)輸出可迭代對(duì)象的元素。
Example:
from itertools import cycle # 無(wú)限循環(huán)輸出 'A', 'B', 'C' for elem in cycle('ABC'): print(elem)
repeat(elem [,n]):
repeat()
函數(shù)生成一個(gè)無(wú)限重復(fù)輸出某個(gè)元素的序列,或者最多重復(fù) n
次。不寫(xiě)n則會(huì)一直重復(fù)
Arguments:
elem
: 要重復(fù)的元素。
n
: 最多重復(fù)的次數(shù),默認(rèn)為無(wú)限次。
Results:
生成一個(gè)無(wú)限重復(fù)輸出元素的序列,或者最多重復(fù) n
次。
Example:
from itertools import repeat # 重復(fù)輸出數(shù)字 10,最多重復(fù) 3 次 for elem in repeat(10, 3): print(elem)
(2)最短序列終止迭代器
1. accumulate(p [,func]):
將可迭代對(duì)象中的元素累積起來(lái),可指定累積的函數(shù)。
Example:
from itertools import accumulate # 累積和 result = accumulate([1, 2, 3, 4, 5]) print(list(result)) # 輸出 [1, 3(1+2), 6(1+2+3), 10, 15]
2. batched(p, n):
將可迭代對(duì)象劃分為大小為 n
的批次。
Example:
from itertools import batched # 劃分為大小為 3 的批次 result = batched('ABCDEFG', n=3) print(list(result)) # 輸出 [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
3. chain(p, q, …):
將多個(gè)可迭代對(duì)象連接成一個(gè)單一的迭代器。
Example:
from itertools import chain # 連接兩個(gè)字符串 result = chain('ABC', 'DEF') print(list(result)) # 輸出 ['A', 'B', 'C', 'D', 'E', 'F']
4. chain.from_iterable(iterable):
與 chain
類似,但接受一個(gè)可迭代對(duì)象的可迭代對(duì)象。
Example:
from itertools import chain # 連接兩個(gè)字符串列表 result = chain.from_iterable(['ABC', 'DEF']) print(list(result)) # 輸出 ['A', 'B', 'C', 'D', 'E', 'F']
5. compress(data, selectors):
返回一個(gè)通過(guò)選擇器篩選的數(shù)據(jù)元素序列。
Example:
from itertools import compress # 通過(guò)選擇器篩選數(shù)據(jù) result = compress('ABCDEF', [1, 0, 1, 0, 1, 1]) # 1有0無(wú) print(list(result)) # 輸出 ['A', 'C', 'E', 'F']
6. dropwhile(pred, seq):
返回在預(yù)測(cè)失敗之后的序列元素。
Example:
from itertools import dropwhile # 在預(yù)測(cè)失敗之后的序列元素 result = dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1]) # 當(dāng)遇到第一個(gè)不滿足條件(即大于等于 5)的元素時(shí),停止迭代并返回余下的元素 [6, 4, 1] print(list(result)) # 輸出 [6, 4, 1]
7. filterfalse(pred, seq):
返回使預(yù)測(cè)結(jié)果為假的序列元素。
Example:
from itertools import filterfalse # 使預(yù)測(cè)結(jié)果為假的序列元素 result = filterfalse(lambda x: x % 2, range(10)) # 與2取模,奇數(shù)會(huì)留1所以不顯示 print(list(result)) # 輸出 [0, 2, 4, 6, 8]
8. groupby(iterable[, key]):
根據(jù)鍵函數(shù)對(duì)序列進(jìn)行分組。
筆者記得,力扣有一道壓縮算法,比如sss44444改為s3,45,就可以拿這個(gè)做,
Example:
from itertools import groupby # 根據(jù)首字母分組 result = groupby('AAAABBBCCDAABBB') for key, group in result: print(key, list(group)) # 輸出 # A ['A', 'A', 'A', 'A'] # B ['B', 'B', 'B'] # C ['C', 'C'] # D ['D'] # A ['A', 'A'] # B ['B', 'B', 'B']
9. islice(seq, [start,] stop [, step]):
返回切片后的序列元素。
Example:
from itertools import islice # 切片序列 seq[start:stop:step] result = islice('ABCDEFG', 2, None) # 從索引 = 2開(kāi)始切,這個(gè)跟py自帶的切片一個(gè)道理 print(list(result)) # 輸出 ['C', 'D', 'E', 'F', 'G']
10. pairwise(iterable):
返回序列中兩兩相鄰的元素。
Example:
from itertools import pairwise # 兩兩相鄰的元素 result = pairwise('ABCDEFG') print(list(result)) # 輸出 [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
11. starmap(func, seq):
對(duì)可迭代對(duì)象中的元素應(yīng)用函數(shù),元素以參數(shù)元組的形式傳遞給函數(shù)。
Example:
from itertools import starmap # 應(yīng)用 pow 函數(shù) result = starmap(pow, [(2, 5), (3, 2), (10, 3)]) # 很好理解,本質(zhì)就是一個(gè)map操作 print(list(result)) # 輸出 [32, 9, 1000]
12. takewhile(pred, seq):
返回在預(yù)測(cè)失敗之前的序列元素立即為。
Example:
from itertools import takewhile # 在預(yù)測(cè)失敗之前的序列元素 result = takewhile(lambda x: x < 5, [1, 4, 6, 4, 1]) print(list(result)) # 輸出 [1, 4]
13. tee(it, n):
將一個(gè)迭代器拆分成多個(gè)相同的迭代器。
Example:
from itertools import tee # 將一個(gè)迭代器拆分成兩個(gè) iter1, iter2 = tee('ABC') print(list(iter1)) # 輸出 ['A', 'B', 'C'] print(list(iter2)) # 輸出 ['A', 'B', 'C']
14. zip_longest(p, q, …):
將多個(gè)迭代器中的元素逐個(gè)配對(duì),以最長(zhǎng)的迭代器為準(zhǔn),可以指定填充值。
Example:
from itertools import zip_longest # 將兩個(gè)迭代器中的元素逐個(gè)配對(duì) result = zip_longest('ABCD', 'xy', fillvalue='-') print(list(result)) # 輸出 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]
(3)排列、組合、笛卡爾積
1. product(p, q, …, repeat=1):
product
函數(shù)用于計(jì)算多個(gè)可迭代對(duì)象的笛卡爾積,生成所有可能的組合。它的參數(shù)可以是多個(gè)可迭代對(duì)象,如p, q, ...
,以及一個(gè)可選的repeat
參數(shù),用于指定重復(fù)的次數(shù)。- 例如,如果
p
是[1, 2]
,q
是[3, 4]
,那么product(p, q)
將生成[(1, 3), (1, 4), (2, 3), (2, 4)]
# 示例 1: product p = [1, 2] q = [3, 4] result_product = list(itertools.product(p, q)) print(result_product) # 輸出:[(1, 3), (1, 4), (2, 3), (2, 4)]
2. permutations(iterable, r=None):
permutations
函數(shù)用于生成可迭代對(duì)象中長(zhǎng)度為r
的所有排列。它的參數(shù)包括一個(gè)可迭代對(duì)象iterable
和一個(gè)可選的r
參數(shù),用于指定生成的排列長(zhǎng)度。- 例如,如果
iterable
是[1, 2, 3]
,r
是2
,那么permutations(iterable, r)
將生成[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
,這是長(zhǎng)度為2
的所有可能排列。
# 示例 2: permutations iterable = [1, 2, 3] r = 2 result_permutations = list(itertools.permutations(iterable, r)) print(result_permutations) # 輸出:[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
3. combinations(iterable, r):
combinations
函數(shù)用于生成可迭代對(duì)象中長(zhǎng)度為r
的所有組合,按照排序順序生成。它的參數(shù)包括一個(gè)可迭代對(duì)象iterable
和一個(gè)r
參數(shù),用于指定生成的組合長(zhǎng)度。- 例如,如果
iterable
是[1, 2, 3]
,r
是2
,那么combinations(iterable, r)
將生成[(1, 2), (1, 3), (2, 3)]
,這是長(zhǎng)度為2
的所有可能組合,按照排序順序生成。
# 示例 3: combinations iterable = [1, 2, 3] r = 2 result_combinations = list(itertools.combinations(iterable, r)) print(result_combinations) # 輸出:[(1, 2), (1, 3), (2, 3)]
4. combinations_with_replacement(iterable, r)
combinations_with_replacement
函數(shù)與combinations
類似,用于生成可迭代對(duì)象中長(zhǎng)度為r
的所有組合,但不要求元素不重復(fù),可以包含重復(fù)元素。- 例如,如果
iterable
是[1, 2]
,r
是2
,那么combinations_with_replacement(iterable, r)
將生成[(1, 1), (1, 2), (2, 2)]
,這是長(zhǎng)度為2
的所有可能組合,包括重復(fù)元素。
# 示例 4: combinations_with_replacement iterable = [1, 2] r = 2 result_combinations_with_replacement = list(itertools.combinations_with_replacement(iterable, r)) print(result_combinations_with_replacement) # 輸出:[(1, 1), (1, 2), (2, 2)]
到此這篇關(guān)于python排列組合庫(kù)itertools的具體使用的文章就介紹到這了,更多相關(guān)python排列組合庫(kù)itertools內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python BeautifulSoup [解決方法] TypeError: list indices must be
這篇文章主要介紹了Python BeautifulSoup [解決方法] TypeError: list indices must be integers or slices, not str,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python線程協(xié)作threading.Condition實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Python線程協(xié)作threading.Condition實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03python郵件中附加文字、html、圖片、附件實(shí)現(xiàn)方法
在本篇文章里小編給大家整理了一篇關(guān)于python郵件中附加文字、html、圖片、附件實(shí)現(xiàn)方法,有興趣的朋友們跟著學(xué)習(xí)下。2021-01-01Python導(dǎo)入模塊時(shí)遇到的錯(cuò)誤分析
這篇文章主要給大家詳細(xì)解釋了在Python處理導(dǎo)入模塊的時(shí)候出現(xiàn)錯(cuò)誤以及具體的情況分析,非常的詳盡,有需要的小伙伴可以參考下2017-08-08Python實(shí)現(xiàn)網(wǎng)頁(yè)文件轉(zhuǎn)PDF文件和PNG圖片的示例代碼
這篇文章主要介紹了如何利用Python分別實(shí)現(xiàn)網(wǎng)頁(yè)文件轉(zhuǎn)為PDF文件和網(wǎng)頁(yè)文件轉(zhuǎn)PNG圖片的示例代碼,文中的代碼簡(jiǎn)潔易懂,感興趣的可以動(dòng)手試試2022-01-01Python開(kāi)發(fā)游戲之井字游戲的實(shí)戰(zhàn)步驟
最近正在學(xué)習(xí)Python,所以最近做了一個(gè)關(guān)于Python的實(shí)例,下面這篇文章主要給大家介紹了關(guān)于Python開(kāi)發(fā)游戲之井字游戲的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02在pyqt5中QLineEdit里面的內(nèi)容回車發(fā)送的實(shí)例
今天小編就為大家分享一篇在pyqt5中QLineEdit里面的內(nèi)容回車發(fā)送的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06Python請(qǐng)求庫(kù)發(fā)送HTTP POST請(qǐng)求的示例代碼
這段代碼使用了Python的requests庫(kù)來(lái)發(fā)送HTTP POST請(qǐng)求,向本地服務(wù)器的API發(fā)送數(shù)據(jù),并處理響應(yīng),一步步解釋這個(gè)代碼2024-08-08