python基礎 - itertools工具

Python的內建模塊itertools提供了非常有用的用於操作迭代對象的函數。

(1)itertools.count()會創建一個無限自然數序列的迭代器,根本停不下來。

itertools.count(1)  # 1,2,3,...

(2)cycle()會把傳入的一個序列無限重複下去

itertools.cycle('ABC') # A,B,C,A,B,C,...

(3)chain()可以把一組迭代對象串聯起來,形成一個更大的迭代器

itertools.chain('ABC', 'XYZ')  # 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'

(4)repeat()負責把一個元素無限重複下去,不過如果提供第二個參數就可以限定重複次數

itertools.repeat('A', 10) # 打印10次'A'

(5)groupby()把迭代器中相鄰的重複元素挑出來放在一起

>>> for key, group in itertools.groupby('AAABBBCCAAA'):
...     print key, list(group) 
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
...     print key, list(group)
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']

(6)imap()map()的區別在於,imap()可以作用於無窮序列,並且,如果兩個序列的長度不一致,以短的那個爲準。

imap()實現了“惰性計算”,也就是在需要獲得結果的時候才計算。

>>> for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
...     print x
...
10
40
90

(7)ifilter()就是filter()的惰性實現。

(8)itertools.product(list1, list2),返回list1、list2中的元素的笛卡爾積的元組。即,依次取出list1中的每1個元素,與list2中的每1個元素,組成元組,然後,將所有的元組組成一個列表,返回。

 >>> for item in itertools.product([1,2,3],[100,200]):
...     print item
...
(1, 100)
(1, 200)
(2, 100)
(2, 200)
(3, 100)
(3, 200)

python字符串中連續相同字符個數:

import itertools
res = [(k, len(list(g))) for k, g in itertools.groupby('TTFTTTFFFFTFFTT')]
res:[('T', 2), ('F', 1), ('T', 3), ('F', 4), ('T', 1), ('F', 2), ('T', 2))]

 


參考:

https://www.liaoxuefeng.com/wiki/897692888725344/983420006222912

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章