容器與可迭代對象
在正式開始前先補充一些基本概念在 Python 中存在容器 與 可迭代對象
- 容器:用來存儲多個元素的數據結構,例如 列表,元組,字典,集合等內容;
- 可迭代對象:實現了 __iter__ 方法的對象就叫做可迭代對象。
從可迭代對象中還衍生出 迭代器 與 生成器:
- 迭代器:既實現了 __iter__,也實現了 __next__ 方法的對象叫做迭代器;
- 生成器:具有 yield 關鍵字的函數都是生成器。
這樣就比較清楚了,可迭代對象的范圍要大于容器。而且可迭代對象只能使用一次,使用完畢再獲取值就會提示 StopIteration 異常。
除此之外,可迭代對象還有一些限制:
- 不能對可迭代對象使用 len 函數;
- 可以使用 next 方法處理可迭代對象,容器也可以通過 iter 函數轉換成迭代器;
- for 語句會自動調用容器的 iter 函數,所以容器也能被循環迭代。
count() 函數
count 函數一般與 range 函數對比學習,例如 range 函數需要定義生成范圍的下限,上限與步長可選,而 count 函數不同,指定下限與步長,上限值不用聲明。
函數原型聲明如下
1
|
count(start = 0 , step = 1 ) - - > count object |
測試代碼如下,其中必須添加跳出循環的判定條件,否則代碼會一直運行下去。
1
2
3
4
5
6
|
from itertools import count a = count( 5 , 10 ) for i in a: print (i) if i > 100 : break |
除此之外,count 函數還接收非整數參數,所以下述代碼中定義的也是正確的。
1
2
3
4
5
6
|
from itertools import count a = count( 0.5 , 0.1 ) for i in a: print (i) if i > 100 : break |
cycle 函數
用 cycle 函數可以循環一組值,測試代碼如下所示:
1
2
3
4
5
6
7
8
|
from itertools import cycle x = cycle( '夢想橡皮擦abcdf' ) for i in range ( 5 ): print ( next (x), end = " " ) print ( "\n" ) print ( "*" * 100 ) for i in range ( 5 ): print ( next (x), end = " " ) |
代碼輸出如下內容:
夢 想 橡 皮 擦
****************************************************************************************************
a b c d f
可以看到 cycle 函數與 for 循環非常類似。
repeat 函數
repeat 函數用于重復返回某個值,官方給出的函數描述如下所示:
1
2
3
4
5
|
class repeat( object ): """ repeat( object [,times]) - > create an iterator which returns the object for the specified number of times. If not specified, returns the object endlessly. |
進行一下簡單的測試,看一下效果:
1
2
3
4
5
6
7
8
|
from itertools import repeat x = repeat( '橡皮擦' ) for i in range ( 5 ): print ( next (x), end = " " ) print ( "\n" ) print ( "*" * 100 ) for i in range ( 5 ): print ( next (x), end = " " ) |
怎么看這個函數,都好像沒有太大用處。
enumerate 函數,添加序號
這個函數在前面的文章中,已經進行過簡單介紹,并且該函數在 __builtins__ 包中,所以不再過多說明,基本格式如下所示:
1
|
enumerate (sequence, [start = 0 ]) |
其中 start 參數是下標起始位置。
accumulate 函數
該函數基于給定的函數返回一個可迭代對象,默認是累加效果,即第二個參數為 operator.add,測試代碼如下:
1
2
3
4
|
from itertools import accumulate data = [ 1 , 2 , 3 , 4 , 5 ] # 計算累積和 print ( list (accumulate(data))) # [1, 3, 6, 10, 15] |
針對上述代碼,修改為累積。
1
2
3
4
5
|
from itertools import accumulate import operator data = [ 1 , 2 , 3 , 4 , 5 ] # 計算累積 print ( list (accumulate(data, operator.mul))) |
除此之外,第二個參數還可以為 max,min 等函數,例如下述代碼:
1
2
3
|
from itertools import accumulate data = [ 1 , 4 , 3 , 2 , 5 ] print ( list (accumulate(data, max ))) |
代碼輸出如下內容,其實是將 data 里面的任意兩個值進行了比較,然后留下最大的值。
[1, 4, 4, 4, 5]
chain 與 groupby 函數
chain 函數用于將多個迭代器組合為單個迭代器,而 groupby 可以將一個迭代器且分為多個子迭代器。
首先展示一下 groupby 函數的應用:
1
2
3
|
from itertools import groupby a = list (groupby( '橡橡皮皮擦擦' )) print (a) |
輸出內容如下所示:
[('橡', <itertools._grouper object at 0x0000000001DD9438>),
('皮', <itertools._grouper object at 0x0000000001DD9278>),
('擦', <itertools._grouper object at 0x00000000021FF710>)]
為了使用 groupby 函數,建議先對原列表進行排序,因為它是有點像切片一樣,發現不同的就分出一個迭代器。
chain 函數的用法如下,將多個迭代對象進行拼接:
1
2
3
|
from itertools import groupby, chain a = list (chain( 'ABC' , 'AAA' , range ( 1 , 3 ))) print (a) |
zip_longest 與 zip
zip 函數在之前的博客中已經進行過說明,zip_longest 與 zip 的區別就是,zip 返回的結果以最短的序列為準,而 zip_longest 以最長的為準。
測試代碼如下,自行比對結果即可。
1
2
3
4
5
|
from itertools import zip_longest a = list ( zip ( 'ABC' , range ( 5 ), [ 10 , 20 , 30 , 40 ])) print (a) a = list (zip_longest( 'ABC' , range ( 5 ), [ 10 , 20 , 30 , 40 ])) print (a) |
zip_logest 如果碰到長度不一致的序列,缺少部分會填充 None。
tee 函數
tee 函數可以克隆可迭代對象,產出多個生成器,每個生成器都可以產出輸入的各個元素。
1
2
3
|
from itertools import tee a = list (tee( '橡皮擦' )) print (a) |
compress 函數
該函數通過**謂詞(是否,True/False)**來確定對某個元素的取舍問題,最簡單的代碼如下所示:
1
2
3
|
from itertools import compress a = list (compress( '橡皮擦' , ( 0 , 1 , 1 ))) print (a) |
islice、dropwhile、takewhile、filterfalse、filter
這幾個函數都是從輸入的可迭代對象中獲取一個子集,而且不修改元素本身。
本部分只羅列各個函數的原型聲明,具體用法直接參考使用即可。
1
2
3
4
5
|
islice(iterable, stop) - - > islice object islice(iterable, start, stop[, step]) - - > islice object dropwhile(predicate, iterable) - - > dropwhile object takewhile(predicate, iterable) - - > takewhile object filterfalse(function or None , sequence) - - > filterfalse object |
其中只有 filterfalse 中的參數是函數在前,序列在后。
測試代碼如下,尤其注意第一個參數是 callable 即函數。
1
2
3
|
from itertools import islice, dropwhile, takewhile, filterfalse a = list (filterfalse( lambda x: x in [ "皮" , "擦" ], '橡皮擦' )) print (a) |
總結
以上內容就是本文的全部內容,在使用無限迭代器函數 count,cycle,repeat 的時候,一定要注意即使停止。
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/hihell/article/details/120181580