python itertools迭代器模組
阿新 • • 發佈:2022-02-23
itertools模組
1、建立屬於自己的迭代器,實現遍歷
2、快速&節約記憶體
無限迭代器:
count
cycle
repeat
count返回一系列值,以start引數開始,也可以接受step引數
無step方式:
from itertools import count
for i in count(10):
if i>20:
break
else:
print(i)
結果為:10 11 12 13 14 15 16 17 18 19 20
有step方式:
from itertools import count,islice: for i in islice(count(10),10): print(i) 結果為:10 11 12 13 14 15 16 17 18 19 解析:count從10開始,迭代10次後停止
cycle迭代器可實現在序列上建立無限迴圈的迭代器
用計數的方式實現有限迭代:
from itertools import cycle count =0 for item in cycle("ABCDEFG"): if count >20: break else: print(item) count+=1 結果為:A B C D E F G A B C D E F G A B C D E F G 解析:cycle("ABCDEFG")會生成一個由"A" "B" "C" "D" "E" "F" "G"組成的無限迴圈迭代器,可實現遍歷
用python內建next()函式實現遍歷迭代
from itertools import cycle
list1=["A","B","C","D","E","F","G"]
iterator=cycle(list1)
for i in range(20):
print(next(iterator))
結果為:A B C D E F G A B C D E F G A B C D E F
解析:cycle("ABCDEFG")會生成一個由"A" "B" "C" "D" "E" "F" "G"組成的無限迴圈迭代器,
每次呼叫next()函式會返回迭代器中的下一個值
repeat迭代器返回同一個物件,如不設定次數會無限迭代
指定迭代次數:
from itertools import repeat
iterator=repeat("txd",5)
for i in range(6):
print(next(iterator))
結果:txd txd txd txd txd
第六次執行迭代next()方法時報錯:
Traceback (most recent call last):
File "D:\unitest\exercise\排序.py", line 4, in <module>
print(next(iterator))
StopIteration
解析:由於指定了迭代次數為5,迴圈執行到第6次時會報錯
不指定迭代次數:
from itertools import repeat
iterator=repeat("txd")
for i in range(20):
print(next(iterator))
結果:txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd txd
小小測試一枚