Python標準庫itertools的使用方法
Python標準庫itertools模組介紹
itertools是python內建的模組,使用簡單且功能強大,這裡嘗試彙總整理下,並提供簡單應用示例;如果還不能滿足你的要求,歡迎加入補充。
使用Python標準庫itertools只需簡單一句匯入:import itertools
chain()
與其名稱意義一樣,給它一個列表如 lists/tuples/iterables,連結在一起;返回iterables物件。
letters = ['a','b','c','d','e','f'] booleans = [1,1,1] print(list(itertools.chain(letters,booleans))) #輸出:['a','f',1] print(tuple(itertools.chain(letters,letters[3:]))) #輸出('a','f') print(set(itertools.chain(letters,letters[3:]))) #輸出:{'a','f'} print(list(itertools.chain(letters,letters[3:]))) #輸出:['a','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,1] numbers = [23,20,44,32,7,12] print(list(itertools.filterfalse(None,booleans))) #輸出:[0,0] print(list(itertools.filterfalse(lambda x : x < 20,numbers))) #輸出:[23,32]
compress()
返回我們需要使用的元素,根據b集合中元素真值,返回a集中對應的元素。
print(list(itertools.compress(letters,booleans))) # ['a','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) 14 34 5
repeat()
repeat(object[,times]) 重複times次;
repeat(10,3) --> 10 10 10
dropwhile()
dropwhile(func,seq );當函式f執行返回假時,開始迭代序列
dropwhile(lambda x: x<5,[1,4,6,1]) --> 6 4 1
takewhile()
takewhile(predicate,iterable);返回序列,當predicate為true是截止。
takewhile(lambda x: x<5,1]) --> 1 4
islice()
islice(seq[,start],stop[,step]);返回序列seq的從start開始到stop結束的步長為step的元素的迭代器
for i in islice("abcdef",2):#a,c print i
product()
product(iter1,iter2,... iterN,[repeat=1]);建立一個迭代器,生成表示item1,item2等中的專案的笛卡爾積的元組,repeat是一個關鍵字引數,指定重複生成序列的次數
# product('ABCD','xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2),repeat=3) --> 000 001 010 011 100 101 110 111 for i in product([1,2,3],[4,[6,7]): print i (1,6) (1,7) (1,7) (2,6) (2,7) (3,6) (3,7)
permutations()
permutations(p[,r]);返回p中任意取r個元素做排列的元組的迭代器
for i in permutations([1,3): print i (1,3) (1,3,2) (2,3) (2,1) (3,2) (3,1)
combinations()
combinations(iterable,r);建立一個迭代器,返回iterable中所有長度為r的子序列,返回的子序列中的項按輸入iterable中的順序排序
note:不帶重複
for i in combinations([1,2): print i (1,2) (1,3)
combinations_with_replacement()
同上,帶重複 例子:
for i in combinations_with_replacement([1,1) (1,3) (3,3)
應用示例
求質數序列中1,9,11,13,15三個數之和為35的三個數;
def get_three_data(data_list,amount): for data in list(itertools.combinations(data_list,3)): if sum(data) == amount: print(data) #(7,15)
更多python標準庫使用方法請點選下面的相關文章