![](/img/trans.png)
[英]How to find all combinations of picking one item from the first list and at most n items from the second list
[英]Find all combinations of N items in N groups without duplicates of item combos (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_c3
和a1_c3_b2
是重復的,我不希望在返回的列表中有任何重復。
沒有所有功能的產品(例如a1_b2
或b2
將不是有效產品,因此我不希望返回列表中的那些產品。
我看過itertools,但我被卡住了。 有任何想法嗎?
你肯定想要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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.