2013-09-25 102 views
1

我想找出一種方法來計算某個產品的功能的所有可能的組合,並讓它們作爲列表返回,而不重複。在N組中找到N個項目的所有組合,而不用重複項目組合(python)?

我對這種方式分組的項目(產品功能):

a 
    a1 
    a2 
    a3 

b 
    b1 
    b2 

c 
    c1 
    c2 
    c3 
    c4 

組和項目的數量是未知的,所以實際上N組和N項。

組合的實施例:

# Combinations with 3 groups 
a1_b1_c1 
a1_b2_c1 
a1_b3_c1 
...and so on 

# Combinations with 4 groups 
a1_b1_c1_d1 
a1_b2_c1_d1 
a1_b3_c1_d1 
...and so on 

我會考慮a1_b2_c3a1_c3_b2是重複的,我不希望在返回的列表中的任何重複。

沒有所有功能的產品,如a1_b2b2不會是有效的產品,因此我不希望那些在返回的列表中。

我看過itertools,但我卡住了。 有什麼建議嗎?

+0

['itertools.product'](http://docs.python.org/2/library/itertools.html #itertools.product)? – BrenBarn

+0

是的,就是這樣!謝謝。 – fredrik

回答

3

你一定要itertools.product:

import itertools 

for i in itertools.product(['a1','a2','a3'], ['b1','b2'],['c1','c2','c3','c4']): 
    print '_'.join(i) 

退貨

a1_b1_c1 
a1_b1_c2 
a1_b1_c3 
... 
a3_b2_c1 
a3_b2_c2 
a3_b2_c3 
a3_b2_c4 
+0

完美。非常感謝。 – fredrik