Python itertools库详细教程
前言
-
庫的學習地址:https://pymotw.com/2/itertools/
-
庫的官網地址:https://docs.python.org/2/library/itertools.html
在Python中,迭代器(生成器, iterator)在Python中是一種很常用也很好用的數據結構,比起列表(list)來說,迭代器最大的優勢就是延遲計算,按需使用,從而提高開發體驗和運行效率,以至于在Python 3中map,filter等操作返回的不再是列表而是迭代器,所以,對于讀取大文件或者無限集合,最好是使用迭代器。
Python的內置模塊 itertools 就是用來操作迭代器的一個模塊,包含的函數都是能夠創建迭代器來用于 for循環或者 next(), itertools用于高效循環的迭代函數集合,其中很多函數的作用我們平時要寫很多代碼才能達到,而在運行效率上反而更低,畢竟人家是系統庫。
其itertools庫中的函數主要分為三類,分別為無限迭代器,有限迭代器,組合迭代器。
一.無限迭代器(Infinite Iterators)
這些函數可以生成無限的迭代器,概述如下:
下面詳細學習:
1.count()
count([start=0, step=1]) 接收兩個可選整形參數,第一個指定了迭代開始的值,第二個指定了迭代的步長。此外,start參數默認為0,step參數默認為1,可以根據需要來把這兩個指定為其他值,或者使用默認參數。
import itertools natuals = itertools.count(1) for n in natuals:print(n)if n > 5:break#輸出 1 2 3 4 5 6因為count() 會創建一個無限的迭代器,所以上述代碼會打印出自然數序列,根本停不下來,只能按Ctrl+C退出
2.cycle()
cycle(iterable) 是用一個可迭代對象中的元素來創建一個迭代器,并且復制自己的值,一直無限的重復下去。
import itertools cs = itertools.cycle('ABC') # 注意字符串也是序列的一種 for c in cs:print(c) # 具有無限的輸出,可以按ctrl+c來停止#輸出 'A' 'B' 'C' 'A' 'B' 'C'cycle() 同樣停不下來,需要Ctrl+C停止。
3.repeat()
repeat(ele, [, n])是將一個元素重復 n 遍或者無窮多變,并返回一個迭代器。不過如果提供第二個參數就可以限定重復次數。
ns = itertools.repeat('A', 5) for n in ns:print(n)#輸出 A A A A A無限序列只有在 for 迭代時才會無限的迭代下去,如果只是創建了一個迭代對象,它不會實現把無限個元素生成出來,事實上也不可能在內存中創建無限多個元素。無限序列雖然可以無限迭代下去,但是我們通常會通過 takewhile() 等函數根據條件判斷來截取一個有限的序列:
natuals = itertools.count(1) ns = itertools.takewhile(lambda x: x <= 5, natuals) for n in ns:print n#輸出 1 2 3 4 5二.有限迭代器(Iterators Terminating on the Shortest Input Sequence)
這里的函數有十來個,如下:
下面我們學習幾個常用的:
1.chain()
chain(*iterables)可以把多個可迭代對象組合起來,形成一個更大的迭代器。
比如:
for iter in itertools.chain('lebron', 'james'):print(iter)#輸出 l e b r o n j a m e s2 .groupby()
groupby(iterable, key=None) 可以把相鄰元素按照 key 函數分組,并返回相應的 key 和 groupby,如果key函數為None,則只有相同的元素才能放在一組。
for key, group in itertools.groupby('AAABBBCCAAA'):print(key, list(group)) #輸出 A ['A', 'A', 'A'] B ['B', 'B', 'B'] C ['C', 'C'] A ['A', 'A', 'A']實際上挑選規則是通過函數完成的,只要作用于函數的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函數返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素“A”和‘a’都返回相等的key。
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):print(key, list(group))#輸出 A ['A', 'a', 'a'] B ['B', 'B', 'b'] C ['c', 'C'] A ['A', 'A', 'a']3.itertools.accumulate()
accumulate(iterable, [, func]) 可以計算出一個迭代器,這個迭代器是由特定的二元函數的累計結果生成的,如果不指定的話,默認函數為求和函數。
from itertools import accumulate<br> x = accumulate(range(10)) print(list(x)) [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]如果我們指定這個累計函數,則還能有不同的用法,例如,指定一個最大值函數,或者自己定義的函數。
from itertools import accumulate# x1 = accumulate(range(10), max) # print(list(x1)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]x2 = accumulate(range(10), min) print(list(x2)) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]三.組合迭代器(Combinatoric Iterators)
組合操作包括排列,笛卡爾積,或者一些離散元素的選擇,組合迭代器就是產生這樣序列的迭代器,概述如下:
下面我們來看看常用的幾個函數:
1.product()
product(*iterables, repeat=1)得到的是可迭代對象的笛卡爾積,*iterables參數表示需要多個可迭代對象。這些可迭代對象之間的笛卡爾積,也可以使用 for 循環來實現例如 product(A, B) 與 ((x, y) for x in A for y in B)就實現一樣的功能。
import itertoolsfor i in itertools.product([1,2,3],[4,5,6]):print(i)#輸出 (1, 4) (1, 5) (1, 6) (2, 4) (2, 5) (2, 6) (3, 4) (3, 5) (3, 6)而 repeat() 參數則表示這些可迭代序列重復的次數。例如 product(A, repeat=4)與 product(A, A, A, A)實現的功能一樣。
import itertools for i in itertools.product('ab','cd',repeat = 2):print(i)#輸出 ('a', 'c', 'a', 'c') ('a', 'c', 'a', 'd') ('a', 'c', 'b', 'c') ('a', 'c', 'b', 'd') ('a', 'd', 'a', 'c') ('a', 'd', 'a', 'd') ('a', 'd', 'b', 'c') ('a', 'd', 'b', 'd') ('b', 'c', 'a', 'c') ('b', 'c', 'a', 'd') ('b', 'c', 'b', 'c') ('b', 'c', 'b', 'd') ('b', 'd', 'a', 'c') ('b', 'd', 'a', 'd') ('b', 'd', 'b', 'c') ('b', 'd', 'b', 'd')2.permutations()
permutations(iterable, r=None)返回的是一個可迭代元素的一個排列組合,并且是按照順序的,且不包含重復的結果。
#更多Python相關視頻、資料加群778463939免費獲取 from itertools import permutationsx = permutations((1,2,3)) print(list(x)) [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]當然,第二個參數默認為None,它表示的是返回元組(tuple)的長度,我們來嘗試一下傳入的第二個參數。
from itertools import permutationsx = permutations((1, 2, 3), 2) print(list(x)) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]3.combinations()
combinations(iterable, r) 返回的是可迭代對象所有的長度為 r 的子序列,注意這個與前一個函數 permutations不同,permutations返回的是排列,而 combinations() 返回的是組合。
下面對比一下combinations() 與 permutations() 函數:
from itertools import permutations, combinationsx1 = permutations((1, 2, 3)) x2 = combinations((1, 2, 3), 3) x11 = permutations((1, 2, 3), 2) x22 = combinations((1, 2, 3), 2) print(list(x1)) print(list(x2)) print(list(x11)) print(list(x22)) # [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] # [(1, 2, 3)] # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] # [(1, 2), (1, 3), (2, 3)]4 combinations_with_replacement()
combinations_with_replacement(iterable, r)返回一個可與自身重復的元素組合,用法類似于 combinations。
from itertools import combinations, combinations_with_replacementx1 = combinations((1, 2), 2) x2 = combinations_with_replacement((1, 2), 2) print(list(x1)) print(list(x2)) # [(1, 2)] # [(1, 1), (1, 2), (2, 2)]結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:←點擊左邊藍色文字就可以跳轉觀看了
Python爬蟲案例教程推薦:←點擊左邊藍色文字就可以跳轉觀看了
總結
以上是生活随笔為你收集整理的Python itertools库详细教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python教程:使用生成器重构提取数据
- 下一篇: Python三元运算