Python 进阶之路 (十) 再立Flag, 社区最全的itertools深度解析(中)
前情回顧
大家好,我又回來了。今天我會(huì)繼續(xù)和大家分享itertools這個(gè)神奇的自帶庫(kù),首先,讓我們回顧一下上一期結(jié)尾的時(shí)候我們講到的3個(gè)方法:
- combinations()
- combinations_with_replacement()
- permutations()
讓我們對(duì)這3個(gè)在排列組合中經(jīng)常會(huì)使用到的函數(shù)做個(gè)總結(jié)
combinations()
基礎(chǔ)概念- 模板:combinations(iterable, n)
- 參數(shù):iterable為可迭代的對(duì)象(list,tuple...), n為想要的組合包含的元素?cái)?shù)
- 返回值: 返回在iterable里n個(gè)元素組成的tuple的全部組合(不考慮順序,元素自身不可重復(fù))
這里我們從lst這個(gè)list里面選取所有由兩個(gè)元素組成的組合,得到結(jié)果如圖所示,這里沒有考慮順序,因此我們不會(huì)看到(1,2)和(2,1)被算作兩種組合,元素自身不可重復(fù),所以沒有(1,1),(2,2),(3,3)的組合出現(xiàn)
combinations_with_replacement()
基礎(chǔ)概念- 模板:combinations_with_replacement(iterable, n)
- 參數(shù):iterable為可迭代的對(duì)象(list,tuple...), n為想要的組合包含的元素?cái)?shù)
- 返回值: 返回在iterable里n個(gè)元素組成的tuple的全部組合(不考慮順序,元素自身可重復(fù))
和剛才的區(qū)別是多了(1,1),(2,2),(3,3)的組合,也就是說允許每個(gè)元素自己和自己組合
permutations()
基礎(chǔ)概念- 模板:permutations(iterable, n=None)
- 參數(shù):iterable為可迭代的對(duì)象(list,tuple...), n為想要的組合包含的元素?cái)?shù)
- 返回值: 返回在iterable里n個(gè)元素組成的tuple的全部組合(考慮順序,元素自身不可重復(fù))
我們用permutations得到的結(jié)果是自身元素不能重復(fù)的情況下,一個(gè)iterable里面由n個(gè)元素構(gòu)成的全部組合,考慮順序
不同點(diǎn)匯總
我們這里可以簡(jiǎn)單匯總一下三個(gè)函數(shù)的不同點(diǎn),匯總一張精華滿滿的表格送個(gè)大家,希望大家如果日后有一天需要用到的話可以回來我這里看看,順便給勤勞的博主點(diǎn)個(gè)贊也是好的?
| combinations() | 2 | [1,2,3] | (1, 2), (1, 3), (2, 3) | 元素自身不能重復(fù),不考慮順序 |
| combinations_with_replacement() | 2 | [1,2,3] | (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3) | 元素自身能重復(fù),不考慮順序 |
| permutations() | 2 | [1,2,3] | (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2) | 元素自身不能重復(fù),考慮順序 |
我必須吐槽一下sf的這個(gè)markdown,連個(gè)表格的快捷方式都沒有么。。。。
數(shù)字序列
在完美的收尾了上一期的內(nèi)容后我們可以繼續(xù)前進(jìn)了,使用itertools,我們可以輕松地在無限序列上生成迭代器。接下來我們主要看看和數(shù)字序列相關(guān)的方法和功能。
首先我們來看一個(gè)生成奇數(shù)偶數(shù)的例子,如果不知道itertools的情況下,我們利用生成器的解決方案如下:
def evens():"""Generate even integers, starting with 0."""n = 0while True:yield nn += 2def odds():"""Generate odd integers, starting with 1."""n = 1while True:yield nn += 2evens = evens() even_numbers = list(next(evens) for _ in range(5)) print(even_numbers)odds = odds() odd_numbers = list(next(odds) for _ in range(5)) print(odd_numbers)Out:[0, 2, 4, 6, 8][1, 3, 5, 7, 9]現(xiàn)在我們可以利用itertools里面的it.count()方法進(jìn)行優(yōu)化:
import itertools as itevens = it.count(step=2) even_numbers = list(next(evens) for _ in range(5)) print(even_numbers)odds = it.count(start=1, step=2) odd_numbers = list(next(odds) for _ in range(5)) print(odd_numbers)Out:[0, 2, 4, 6, 8][1, 3, 5, 7, 9]itertools.count()這個(gè)方法主要就是用來計(jì)數(shù),默認(rèn)從0開始,我們可以通過設(shè)置start關(guān)鍵字參數(shù)從任何數(shù)字開始計(jì)數(shù),默認(rèn)為0.同樣也可以設(shè)置step關(guān)鍵字參數(shù)來確定從count()返回的數(shù)字之間的間隔,默認(rèn)為1。
再來看其它兩個(gè)用到itertools count方法的例子:
>>> count_with_floats = it.count(start=0.5, step=0.75) >>> list(next(count_with_floats) for _ in range(5)) [0.5, 1.25, 2.0, 2.75, 3.5]可以用來計(jì)算float類型
>>> negative_count = it.count(start=-1, step=-0.5) >>> list(next(negative_count) for _ in range(5)) [-1, -1.5, -2.0, -2.5, -3.0]或是負(fù)數(shù)也沒有問題
在某些方面,count()類似于內(nèi)置range()函數(shù),但count()總是返回?zé)o限序列。無限序列的好處在于它不可能完全迭代
count()函數(shù)甚至模擬了內(nèi)置的enumrate()功能:
import itertools as it print(list(zip(it.count(), ['a', 'b', 'c'])))Out:[(0, 'a'), (1, 'b'), (2, 'c')]其他有意思的方法
repeat(object, times=1)首先讓我們看一下itertools里面的repeat放法,它的功能是返回一個(gè)值的無限序列:
all_ones = it.repeat(1) # 1, 1, 1, 1, ... all_twos = it.repeat(2) # 2, 2, 2, 2, ...如果我們希望可以指定返回序列的長(zhǎng)度,我們可以在方法的第二個(gè)參數(shù)加上想要的序列長(zhǎng)度即可:
five_ones = it.repeat(1, 5) # 1, 1, 1, 1, 1 three_fours = it.repeat(4, 3) # 4, 4, 4 cycle(iterable)接著估計(jì)你可能想到了,那如果我們想要不斷循環(huán)兩個(gè)數(shù)呢?答案是itertools的cycle方法:
alternating_ones = it.cycle([1, -1]) # 1, -1, 1, -1, 1, -1, ...如果你想要輸出上面的alternating_ones是不可能的,因?yàn)檫@是一個(gè)無限序列,你會(huì)收到下面的錯(cuò)誤:
Traceback (most recent call last):File "C:\Users\Desktop\itertools.py", line 48, in <module>alternating_ones = list(it.cycle([0, 1])) MemoryError accumulate(iterable, func=operator.add)itertools.accumulate()函數(shù), 這個(gè)函數(shù)有些特殊,它接受兩個(gè)參數(shù) :
- 一個(gè)可迭代的輸入
- 一個(gè)二進(jìn)制函數(shù)func(即一個(gè)具有兩個(gè)輸入的函數(shù))
并返回一個(gè)迭代器,用于將func應(yīng)用于輸入元素的累積結(jié)果??匆粋€(gè)小栗子:
>>> import operator >>> list(it.accumulate([1, 2, 3, 4, 5], operator.add)) [1, 3, 6, 10, 15]accumulate()返回的迭代器中的第一個(gè)值始終是輸入序列中的第一個(gè)值。在這個(gè)例子中,是1,因?yàn)?是 [1,2,3,4,5]中的第一個(gè)值。
輸出迭代器中的下一個(gè)值是輸入序列的前兩個(gè)元素的總和:add(1,2)= 3,所以操作模式如下:
- add(3, 3) = add(add(1, 2), 3) = 6
以此類推,最終得到最后的答案。實(shí)際上accumulate()的第二個(gè)參數(shù)本身就是默認(rèn)為operator.add(),因此前面的示例可以簡(jiǎn)化為:
>>> list(it.accumulate([1, 2, 3, 4, 5])) [1, 3, 6, 10, 15]我們也可以自己添加別的方法到第二個(gè)參數(shù)里:
>>> list(it.accumulate([9, 21, 17, 5, 11, 12, 2, 6], min)) [9, 9, 9, 5, 5, 5, 2, 2]好啦,itertools 有關(guān)于數(shù)字序列方面的方法我就簡(jiǎn)單介紹到這里啦,有需要的朋友可以自己去看看,其實(shí)還是非常實(shí)用的,不是類似lambda那些花哨的方法
對(duì)List和字符串的相關(guān)操作
itertools.product 實(shí)現(xiàn)交叉組合 >>> product([1, 2], ['a', 'b']) (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')此處實(shí)現(xiàn)兩個(gè)可迭代序列的元素組合。
itertools.tee 從一個(gè)輸入序列生成任意數(shù)量的生成器 >>> iter1, iter2 = it.tee(['a', 'b', 'c'], 2) >>> list(iter1) ['a', 'b', 'c'] >>> list(iter2) ['a', 'b', 'c']注意這里的iter1和iter2相互不會(huì)一影響。是一個(gè)深復(fù)制
islice(iterable, stop) islice(iterable, start, stop, step=1) 切片 >>> islice([1, 2, 3, 4], 3) 1, 2, 3>>> islice([1, 2, 3, 4], 1, 2) 2, 3這里和list最大的區(qū)別在于返回對(duì)象是一個(gè)迭代器,并不是一個(gè)list,islice(iterable, stop)中stop是切片截至的index,和list切片一樣,并不會(huì)包括stop本身的值。如果想要指定切片起始位置和不長(zhǎng),就使用islice(iterable, start, stop, step=1)
chain(*iterables) >>> chain('abc', [1, 2, 3]) #<type 'itertools.chain'> 'a', 'b', 'c', 1, 2, 3返回一個(gè)鏈對(duì)象,其__next __()方法返回第一個(gè)iterable中的元素,直到它耗盡,然后是來自下一個(gè)iterable的元素,直到所有的iterables都用完為止。
這里有一點(diǎn)需要注意,chain()函數(shù)有一個(gè)類方法.from_iterable(),它將一個(gè)iterable作為參數(shù)。迭代的元素本身必須是可迭代的,因此效應(yīng)是chain.from_iterable()某種程度上可以實(shí)現(xiàn)類似 list.extend() 或者 list.append() 的功能, 我們一起看一個(gè)混合了很多itertools中其他方法的綜合小栗子:
import itertools as it cycle = it.chain.from_iterable(it.repeat('abc')) result = list(it.islice(cycle,8)) print(result)Out: ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b']這里其實(shí)it.chain.from_iterable里面甚至可以放進(jìn)一個(gè)無限序列,不一定是定長(zhǎng)的。
總結(jié)
這一期的內(nèi)容沒有那么長(zhǎng),我們簡(jiǎn)單了解了一下itertools的基礎(chǔ)好用的方法,下一期就是簡(jiǎn)單實(shí)戰(zhàn)了,我自己在網(wǎng)上找了一些非常不錯(cuò)的案例,照貓畫虎練習(xí)了一下,打算在下一期和大家一起分享。這次的文章就到這里啦,我們下期見!!!
總結(jié)
以上是生活随笔為你收集整理的Python 进阶之路 (十) 再立Flag, 社区最全的itertools深度解析(中)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数码管基础知识
- 下一篇: regex_search