python 常用內建函式itertools

2021-08-26 05:30:27 字數 2880 閱讀 3440

參考文章:

python 內建的 itertools 模組包含了一系列用來產生不同型別迭代器的函式或類,這些函式的返回都是乙個迭代器,我們可以通過 for 迴圈來遍歷取值,也可以使用 next() 來取值。

itertools 模組提供的迭代器函式有以下幾種型別:

無限迭代器:生成乙個無限序列,比如自然數序列 1, 2, 3, 4, …;

有限迭代器:接收乙個或多個序列(sequence)作為引數,進行組合、分組和過濾等;

組合生成器:序列的排列、組合,求序列的笛卡兒積等;

8.28 2018

先看看組合生成器

itertools 模組提供了多個組合生成器函式,用於求序列的排列、組合等:

product

permutations

combinations

combinations_with_replacement

1.product

product 用於求多個可迭代物件的笛卡爾積,它跟巢狀的 for 迴圈等價。它的一般使用形式如下:

product(iter1, iter2, ... itern, [repeat=1])
其中,repeat 是乙個關鍵字引數,用於指定重複生成序列的次數

>>> 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')]

>>>

2.permutations

permutations 用於生成乙個排列,它的一般使用形式如下:

permutations

(iterable[, r])

其中,r 指定生成排列的元素的長度,如果不指定,則預設為可迭代物件的元素長度。

>>> 

from itertools import permutations

>>>

>>> permutations('abc', 2)

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')]

>>>

3.combinations

combinations 用於求序列的組合,它的使用形式如下:

combinations

(iterable, r)

其中,r 指定生成組合的元素的長度。

>>> 

from itertools import combinations

>>>

>>> list(combinations('abc', 2))

[('a', 'b'), ('a', 'c'), ('b', 'c')]

4.combinations_with_replacement

combinations_with_replacement 和 combinations 類似,但它生成的組合包含自身元素。

>>> 

from itertools import combinations_with_replacement

>>>

>>> list(combinations_with_replacement('abc', 2))

[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

Python常用內建函式

1 絕對值 abs 1 2 最大最小值 max 1,2,3 min 1,2,3 3 序列長度 len abc len 1,2,3 len 1,2,3 4 取模 divmod 5,2 2,1 5 乘方 pow 2,3,4 2 3 4 6 浮點數 round 1 1 函式是否可呼叫 callable f...

python常用內建函式

locals 當前作用域內所有變數 globals 全域性所有變數 next 迭代器 iter 可迭代物件 range dir 檢視乙個物件擁有的屬性 callable 括號內為可呼叫函式時返回true help open writable readable hash 括號內必須為乙個可雜湊型別 e...

python 常用內建函式

getitem 支援物件可迭代 setitem 支援可變序列協議 iter 返回 self,以便在應該使用可迭代物件的地方使用迭代器,例如在 for 迴圈中 getattr setattr repr 以便於開發者理解的方式返回物件的字串表示形式 str 以便於使用者理解的方式返回物件的字串表示形式 ...