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