python 排列組合

在itertools迭代工具中,有排列組合的方法:

.product排列 有放回抽樣排列
.permutations 排列 不放回抽樣排列
.combinations 組合 不放回抽樣組合
combinations_with_replacement 組合   有放回抽樣組合

 

前兩個與後兩個是有區別的,

前兩個爲均是從0位開始迭代,故有重複,稱作排列

後兩個是從迭代位逐個開始迭代,沒有重複,稱作組合

itertools.product

有放回的抽樣排列,返回類型是itertools.product的tuple組合,

挑幾句product定義:

1.For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).

2.For example, product(A, repeat=4) means the same as product(A, A, A, A).

3.product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)

   product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0)

也就是說,實際上,只有一種迭代方式,傳入數組(A,B)

在自身迭代的時候,可以用,repead = 4  把(A,A,A,A)代替了,二者都是按順序進行迭代。

import  itertools as itl
A = range(3)
B = itl.product(A,repeat=2)
print("B的類型是:",type(B))
for i in B :
    print(i)
print("B中單元類型是:",type(i))

itertools.permutations  

不放回的迭代,返回類型是itertools.product的tuple組合,

挑幾句permutations的定義:

permutations(iterable[, r]) --> permutations object
Return successive r-length permutations of elements in the iterable.

對數列進行-1迭代,傳入r爲Int類型

import  itertools as itl
A = range(3)
B = itl.permutations(A,2)
print("B的類型是:",type(B))
for i in B :
    print(i)
print("B中單元類型是:",type(i))

itertools.combinations 組合,沒有重複 

無放回,

combinations(iterable, r) --> combinations object

Return successive r-length combinations of elements in the iterable.

combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)

意思和上面差不多,但是效果沒有重複,與排列不同的叫做組合。

import  itertools as itl
A = range(3)
B = itl.combinations(A,2)
print("B的類型是:",type(B))
for i in B :
    print(i)
print("B中單元類型是:",type(i))

itertools.combinations_with_replacement

combinations_with_replacement(iterable, r) --> combinations_with_replacement object

Return successive r-length combinations of elements in the iterable
allowing individual elements to have successive repeats.
combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC

意思都差不多,直接上圖|:

import  itertools as itl
A = range(3)
B = itl.combinations_with_replacement(A,2)
print("B的類型是:",type(B))
for i in B :
    print(i)
print("B中單元類型是:",type(i))

 

 

介紹完畢,需要注意的是,返回的B並不是List列表,如果需要可以進行類型轉換。

 

 

 

 

 

 

 

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