itertools拼裝迭代器
連接多個迭代器
內置的itertools模塊有一些函數可以把多個迭代器連城一個使用。
chain
chain可以把多個迭代器從頭到尾連成一個迭代器。
import itertoolsit = itertools.chain([1, 2, 3], [4, 5, 6])
print(list(it))>>>
[1, 2, 3, 4, 5, 6]
repeat
Repeat可以制作這樣一個迭代器,它會不停地輸出某個值。調用repeat時,也可以通過第二個參數指定迭代器最多能輸出幾次。
it = itertools.repeat('hello', 3)
print(list(it))>>>
['hello', 'hello', 'hello']
cycle
cycle可以制作這樣一個迭代器,它會循環地輸出某段內容之中的各項元素。
it = itertools.cycle([1, 2])
result = [next(it) for _ in range(10)]
print(result)>>>
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
tee
tee可以讓一個迭代器分裂成多個平行的迭代器,具體個數由第二個參數指定。如果這些迭代器推進的速度不一致,那么程序可能要用大量內存做緩沖,以存放進度落后的迭代器將來會用到的元素。
import itertoolsit1, it2, it3 = itertools.tee(['first', 'second'], 3)
print(list(it1))
print(list(it2))
print(list(it3))>>>
['first', 'second']
['first', 'second']
['first', 'second']
zip_longest
它與Python內置的zip函數類似,但區別在于,如果源迭代器的長度不同,那么它會用fillvalue參數的值來填補提前耗盡的那些迭代器所留下的空缺。
import itertoolskeys = ['one', 'two', 'three', 'four', 'five']
values = [1, 2]normal = list(zip(keys, values))
print('zip: ', normal)it = itertools.zip_longest(keys, values, fillvalue='nope')
longest = list(it)
print('zip_longest: ', longest)>>>
zip: [('one', 1), ('two', 2)]
zip_longest: [('one', 1), ('two', 2), ('three', 'nope'), ('four', 'nope'), ('five', 'nope')]