python模塊-itertools

一、itertools(itertools 模塊提供了很多用於產生多種類型迭代器的函數,它們的返回值不是 list,而是迭代器。)

Python 內置的 itertools 模塊包含了一系列用來產生不同類型迭代器的函數或類,這些函數的返回都是一個迭代器,我們可以通過 for 循環來遍歷取值,也可以使用 next() 來取值。

二、無限迭代器

(一)count() 接收兩個參數,第一個參數指定開始值,默認爲 0,第二個參數指定步長,默認爲 1:

import itertools
nums = itertools.count()
for num in nums:
    if num > 2:
        break
    print num    
# 0,1,2

(二)cycle() 元素反覆執行循環

import itertools

numbers = itertools.cycle("123")
i = 0
data = list()
for num in numbers:
    if i == 6:
        break
    i += 1
    data.extend((i, num))
print data
# [1, '1', 2, '2', 3, '3', 4, '1', 5, '2', 6, '3']

(三)repeat() 反覆生成一個 object

import itertools
datas = itertools.repeat('nihao', 3)

for data in datas:
    print data
# nihao
# nihao
# nihao

三、有限迭代器

(一)chain 接收多個可迭代對象作爲參數,將它們連接起來,作爲一個新的迭代器返回。

from itertools import chain
for item in chain([1, 2, 3], ['a', 'b', 'c']):
     print item
...
1
2
3
a
b
c

(二)compress(data, selectors) 對數據進行篩選,當 selectors 的某個元素爲 true 時,則保留 data 對應位置的元素,否則去除。

>>> from itertools import compress
>>>
>>> list(compress('ABCDEF', [1, 1, 0, 1, 0, 1]))
['A', 'B', 'D', 'F']
>>> list(compress('ABCDEF', [1, 1, 0, 1]))
['A', 'B', 'D']
>>> list(compress('ABCDEF', [True, False, True]))
['A', 'C']

(三)dropwhile(predicate, iterable) predicate 是函數,iterable 是可迭代對象。對於 iterable 中的元素,如果 predicate(item) 爲 true,則丟棄該元素,否則返回該項及所有後續項。

>>> from itertools import dropwhile
>>>
>>> list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
[6, 2, 1]

(四)islice(iterable, [start,] stop [, step]) iterable 是可迭代對象,start 是開始索引,stop 是結束索引,step 是步長,start 和 step 可選。

>>> from itertools import islice
>>>
>>> list(islice([10, 6, 2, 8, 1, 3, 9], 5))
[10, 6, 2, 8, 1]

(五)imap(func, iter1, iter2, iter3, …) imap 返回一個迭代器,元素爲 func(i1, i2, i3, …),i1,i2 等分別來源於 iter, iter2。

>>> from itertools import imap
>>>
>>> imap(str, [1, 2, 3, 4])
<itertools.imap object at 0x10556d050>
>>>
>>> list(imap(str, [1, 2, 3, 4]))
['1', '2', '3', '4']
>>>
>>> list(imap(pow, [2, 3, 10], [4, 2, 3]))
[16, 9, 1000]

(六)tee(iterable [,n]) 用於從 iterable 創建 n 個獨立的迭代器,以元組的形式返回,n 的默認值是 2。

>>> from itertools import tee
>>>
>>> tee('abcd')   # n 默認爲 2,創建兩個獨立的迭代器
(<itertools.tee object at 0x1049957e8>, <itertools.tee object at 0x104995878>)
>>>
>>> iter1, iter2 = tee('abcde')
>>> list(iter1)
['a', 'b', 'c', 'd', 'e']
>>> list(iter2)
['a', 'b', 'c', 'd', 'e']
>>>
>>> tee('abc', 3)  # 創建三個獨立的迭代器
(<itertools.tee object at 0x104995998>, <itertools.tee object at 0x1049959e0>, <itertools.tee object at 0x104995a28>)

(七)takewhile(predicate, iterable) predicate 是函數,iterable 是可迭代對象。對於 iterable 中的元素,如果 predicate(item) 爲 true,則保留該元素,只要 predicate(item) 爲 false,則立即停止迭代。

>>> from itertools import takewhile
>>>
>>> list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
[1, 3]
>>> list(takewhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
[]

(八)izip(iter1, iter2, …, iterN) izip 用於將多個可迭代對象對應位置的元素作爲一個元組,將所有元組『組成』一個迭代器,並返回。它的使用形式如下。

>>> from itertools import izip
>>> 
>>> for item in izip('ABCD', 'xy'):
...     print item
...
('A', 'x')
('B', 'y')
>>> for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
...     print item
...
(1, 'a')
(2, 'b')
(3, 'c')

四、組合生成器

(一)product(iter1, iter2, … iterN, [repeat=1]) 用於求多個可迭代對象的笛卡爾積,它跟嵌套的 for 循環等價。

>>> from itertools import product
>>>
>>> for item in product('ABCD', 'xy'):
...     print item
...
('A', 'x')
('A', 'y')
('B', 'x')
('B', 'y')
('C', 'x')
('C', 'y')
('D', 'x')
('D', 'y')
>>>
>>> list(product('ab', range(3)))
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2)]
>>>
>>> list(product((0,1), (0,1), (0,1)))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
>>>
>>> list(product('ABC', repeat=2))
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

(二)permutations(iterable[, r]) 用於生成一個排列。r 指定生成排列的元素的長度,如果不指定,則默認爲可迭代對象的元素長度。

>>> from itertools import permutations
>>>
>>> permutations('ABC', 2)
<itertools.permutations object at 0x1074d9c50>
>>>
>>> list(permutations('ABC', 2))
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
>>>
>>> list(permutations('ABC'))
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
>>>

(三)combinations(iterable, r) 用於求序列的組合。

>>> from itertools import combinations
>>>
>>> list(combinations('ABC', 2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章