介紹
itertools是python內置的模塊,使用簡單且功能強大,這里嘗試匯總整理下,并提供簡單應用示例;如果還不能滿足你的要求,歡迎加入補充。
使用只需簡單一句導入:import itertools
chain()
與其名稱意義一樣,給它一個列表如 lists/tuples/iterables,鏈接在一起;返回iterables對象。
letters = ['a', 'b', 'c', 'd', 'e', 'f']booleans = [1, 0, 1, 0, 0, 1] print(list(itertools.chain(letters,booleans)))# ['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1] print(tuple(itertools.chain(letters,letters[3:])))# ('a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f') print(set(itertools.chain(letters,letters[3:])))# {'a', 'd', 'b', 'e', 'c', 'f'} print(list(itertools.chain(letters,letters[3:])))# ['a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f'] for item in list(itertools.chain(letters,booleans)): print(item)
count()
生成無界限序列,count(start=0, step=1) ,示例從100開始,步長為2,循環10,打印對應值;必須手動break,count()會一直循環。
i = 0 for item in itertools.count(100,2): i += 1 if i > 10 : break print(item) filterfalse () Python filterfalse(contintion,data) 迭代過濾條件為false的數據。如果條件為空,返回data中為false的項;booleans = [1, 0, 1, 0, 0, 1]numbers = [23, 20, 44, 32, 7, 12] print(list(itertools.filterfalse(None,booleans)))# [0, 0, 0]print(list(itertools.filterfalse(lambda x : x < 20,numbers)))# [23, 20, 44, 32]
compress()
返回我們需要使用的元素,根據b集合中元素真值,返回a集中對應的元素。
print(list(itertools.compress(letters,booleans)))# ['a', 'c', 'f']
starmap()
針對list中的每一項,調用函數功能。starmap(func,list[]) ;
starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 >>> from itertools import *>>> x = starmap(max,[[5,14,5],[2,34,6],[3,5,2]])>>> for i in x:>>> print (i)14345repeat()repeat(object[, times]) 重復times次;repeat(10, 3) --> 10 10 10dropwhile()dropwhile(func, seq );當函數f執行返回假時, 開始迭代序列dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1takewhile()takewhile(predicate, iterable);返回序列,當predicate為true是截止。takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4islice()islice(seq[, start], stop[, step]);返回序列seq的從start開始到stop結束的步長為step的元素的迭代器for i in islice("abcdef", 0, 4, 2):#a, c print i
product()
product(iter1,iter2, ... iterN, [repeat=1]);創建一個迭代器,生成表示item1,item2等中的項目的笛卡爾積的元組,repeat是一個關鍵字參數,指定重復生成序列的次數
新聞熱點
疑難解答