簡介
Python 有很多內(nèi)置工具谐丢,允許我們迭代和轉(zhuǎn)換數(shù)據(jù)爽航。比如itertools模塊,它提供了幾個方便的迭代函數(shù)乾忱。每個迭代器構(gòu)建函數(shù)都可以單獨使用讥珍,也可以組合使用。
該模塊的靈感來自于函數(shù)式語言窄瘟,如APL衷佃、Haskell 和 SPL。
Iterable vs Iterator
iterable是可迭代的對象蹄葱。當(dāng)使用iter()函數(shù)時氏义,生成迭代器。一般來說图云,大多數(shù)序列都是可迭代的惯悠,如列表、元組竣况、字符串等克婶。
iterator來迭代可迭代的序列,迭代器也可以迭代自己帕翻,可以通過使用next()方法來實現(xiàn)鸠补,傳入我們要遍歷的迭代器。
>>> list = [1,2,3,4,5]
>>> iterator = iter(list)
>>> print(iterator)
<list_iterator object at 0x7f96d5ed66d0>
>>> print(next(iterator))
1
count()
count(start, step)函數(shù)創(chuàng)建了代器嘀掸,用于生成均勻間隔的值紫岩,它們之間的空間由step參數(shù)定義。start參數(shù)定義了迭代器的起始值--默認(rèn)情況下睬塌,這些參數(shù)被設(shè)置為start=0泉蝌,step=1。
如果沒有中斷條件揩晴,count()函數(shù)將無限計數(shù)(受限于內(nèi)存)勋陪。
>>> from itertools import count
>>>
>>> iterator_count = count(start=0, step=5)
>>>
>>> for i in iterator_count:
... if(i == 25):
... break
... print(i)
...
0
5
10
15
20
該函最常與其他函數(shù)一起使用。
例如硫兰,當(dāng)使用zip()將一個列表的多個項目壓縮在一起時诅愚,你可能想通過一個位置索引來注釋它們。在壓縮的時候劫映,我們會用count()來生成這些索引的值违孝。
>>> from itertools import count
>>>
>>> list = ['John', 'Marie', 'Jack', 'Anna']
>>> for i in zip(count(), list):
... print(i)
...
(0, 'John')
(1, 'Marie')
(2, 'Jack')
(3, 'Anna')
>>> for i in zip(range(10), list):
... print(i)
...
(0, 'John')
(1, 'Marie')
(2, 'Jack')
(3, 'Anna')
是不是和內(nèi)置函數(shù)range和類似刹前,只是更簡單一點。因為這個原因雌桑,很多人使用range而不是count喇喉。不過count支持小數(shù):
>>> for i in zip(count(1, 0.1), ['a', 'b', 'c']):
... print('{:.2f}: {}'.format(*i))
...
1.00: a
1.10: b
1.20: c
cycle()函數(shù)
cycle()函數(shù)接受iterable并生成一iterator,它包含了迭代器的所有元素校坑。
一旦我們迭代到元素的末尾拣技,我們就開始迭代這些副本。在迭代副本的過程中耍目,會產(chǎn)生新的副本膏斤。一旦第一組副本用完,我們就迭代新的一組制妄。這個過程無限重復(fù)掸绞。
使用cycle()泵三,特別是對較長的序列來說耕捞,是非常耗費內(nèi)存的。小心無限的烫幕、遞歸的創(chuàng)建邏輯俺抽,因為會耗盡內(nèi)存。
from itertools import cycle
list = [1,2,3,4]
iterator = cycle(list)
for i in iterator:
print(i)
結(jié)果
1
2
3
4
1
2
3
4
...
直到我們終止程序或耗盡內(nèi)存较曼。也就是說--你應(yīng)該始終為cycle()函數(shù)設(shè)置退出/終止條件磷斧。
repeat()函數(shù)
cycle占用內(nèi)存太多,可以用repeat控制數(shù)量
>>> from itertools import repeat
>>>
>>> for i in repeat('over-and-over', 5):
... print(i)
...
over-and-over
over-and-over
over-and-over
over-and-over
over-and-over
# repeat在只傳入一個參數(shù)的時候捷犹,表示循環(huán)該值
>>> for i in map(lambda x, y: (x, y, x * y), repeat(2), range(5)):
... print('{:d} * {:d} = {:d}'.format(*i))
...
2 * 0 = 0
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
參考資料
- 本文涉及的python測試開發(fā)庫 謝謝點贊弛饭!
- 本文相關(guān)海量書籍下載
- https://pymotw.com/3/itertools/index.html
- https://stackabuse.com/pythons-itertools-count-cycle-and-chain
chain()函數(shù)
chain()函數(shù)用于將多個iterable連接一起,通過生成一個迭代器萍歉,一個接一個地依次遍歷它們侣颂。
from itertools import chain
result = list(chain([1, 2, 3],
["one", "two", "three"],
"String",
("this", "is", "a", "tuple")))
print(result)
結(jié)果
[1, 2, 3, 'one', 'two', 'three', 'S', 't', 'r', 'i', 'n', 'g', 'this', 'is', 'a', 'tuple']
更多例子
from itertools import chain
result2 = list(chain(["one", "two", "three"]))
result3 = list(chain.from_iterable(["one", "two", "three"]))
print(result2)
print(result3)
number_list = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
result = list(chain.from_iterable(number_list))
print(sum(result))
結(jié)果
['one', 'two', 'three']
['o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e']
45