[英]Find all combinations of N items in N groups without duplicates of item combos (python)?
I'm trying to figure out a way of calculating all possible combinations of features of a certain product and have them returned as a list, without duplicates. 我试图找出一种计算某种产品功能的所有可能组合的方法,并将它们作为列表返回,没有重复。
I have the items (features of the product) grouped in this kind of manner: 我有以这种方式分组的项目(产品的功能):
a
a1
a2
a3
b
b1
b2
c
c1
c2
c3
c4
The number of groups and items are unknown, so there are in fact N groups and N items. 组和项目的数量是未知的,因此实际上有N组和N项。
Example combinations: 示例组合:
# 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
I would consider a1_b2_c3
and a1_c3_b2
to be duplicates, and I would not want any duplicates in the returned list. 我会认为
a1_b2_c3
和a1_c3_b2
是重复的,我不希望在返回的列表中有任何重复。
A product without all features, such as a1_b2
or b2
would not be a valid product and thus I do not want those in the returned list either. 没有所有功能的产品(例如
a1_b2
或b2
将不是有效产品,因此我不希望返回列表中的那些产品。
I've looked into itertools but I'm stuck. 我看过itertools,但我被卡住了。 Any ideas?
有任何想法吗?
You definitely want itertools.product: 你肯定想要itertools.product:
import itertools
for i in itertools.product(['a1','a2','a3'], ['b1','b2'],['c1','c2','c3','c4']):
print '_'.join(i)
RETURNS 退货
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.