2013-07-11 24 views
0

我需要從具有選項的空間中生成所有可能的組合,並且每個選項都有自己的值。來自配置空間模型的所有可能的組合

作爲一個例子,

option 1: {1,2,3} 
option 2: {4,5} 
option 3: {2,3} 

組合都將是在格式,(V1,V2,V3),其爲v1,v2和v3從選項1,選項2和選項3是來分別。我將輸出12個列表如下:

(1,4,2), (1,4,3), (1,5,2), (1,5,3), (2,4,2), (2,4,3), (2,5,2), (2,5,3), (3,4,2), (3,4,3), (3,5,2), (3,5,3) 

我該怎麼做?

+0

這就是所謂的笛卡爾乘積。因此,itertools.product –

回答

2

使用itertools.product()以產生所有的組合:

>>> from itertools import product 
>>> option1 = {1, 2, 3} 
>>> option2 = {4, 5} 
>>> option3 = {2, 3} 
>>> for tup in product(option1, option2, option3): 
...  print tup 
... 
(1, 4, 2) 
(1, 4, 3) 
(1, 5, 2) 
(1, 5, 3) 
(2, 4, 2) 
(2, 4, 3) 
(2, 5, 2) 
(2, 5, 3) 
(3, 4, 2) 
(3, 4, 3) 
(3, 5, 2) 
(3, 5, 3) 

itertools.product()發生器;當for循環遍歷它時,它會根據需要生成組合,或者每次使用next()函數時都可以要求它提供新組合。這使得itertools.product()非常有效。因爲它完全是用C實現的,所以itertools.product()也很快快,,比列表理解更快。

要生成一個列表,通話list()它:itertools.product和列表理解之間

>>> list(product(option1, option2, option3)) 
[(1, 4, 2), (1, 4, 3), (1, 5, 2), (1, 5, 3), (2, 4, 2), (2, 4, 3), (2, 5, 2), (2, 5, 3), (3, 4, 2), (3, 4, 3), (3, 5, 2), (3, 5, 3)] 

時間比較:

>>> timeit.timeit("list(product(option1, option2, option3))", "from __main__ import option1, option2, option3, product") 
1.6326439380645752 
>>> timeit.timeit("[(x, y, z) for x in option1 for y in option2 for z in option3]", "from __main__ import option1, option2, option3, product") 
2.2882919311523438 
+0

的名稱謝謝,這將對我有用。 – genclik27

0

您可以使用Python Comprehension它做。

>>> op1 = {1,2,3} 
>>> op2 = {4,5} 
>>> op3={2,3} 
>>> ans = [(x,y,z) for x in op1 for y in op2 for z in op3] 
>>> ans 
[(1, 4, 2), (1, 4, 3), (1, 5, 2), (1, 5, 3), (2, 4, 2), (2, 4, 3), (2, 5, 2), (2 
, 5, 3), (3, 4, 2), (3, 4, 3), (3, 5, 2), (3, 5, 3)] 

上述一行的答案是

[(x,y,z) for x in {1,2,3} for y in {4,5} for z in {2,3}] 
+1

+1使用列表理解 –

+1

-1使用列表理解;) – georg

+0

選項和值的數量不固定。其實我會用這個大空間。所以我認爲使用itertools.product()更好。不管怎麼說,還是要謝謝你 – genclik27