我有一组数字[1, 2, 4, 1]
。现在,我想从这个大小为k(例如k= 3)的集合中生成所有可能的组合。所有生成的输出集不能重复
示例:[1, 2, 1]
和[2, 1, 1]
是相同的集合,但不应选择它们。它们中只有一个应该出现。在Python中使用itertools的组合是可能的吗?
import itertools
x = [1, 2, 1]
print([p for p in itertools.product(x, repeat=3)])
我尝试过使用itertools.product,但它不起作用,使用itertools中的组合会得到重复的结果
我尝试过使用itertools.combinations print([p for p in set(itertools.combinations(x, r=3))])
如果我给出以下输入
x = [-1, 0, 1, 2, -1, -4]
R=3时生成的输出为
[(0, -1, -4), (-1, -1, -4), (-1, 1, -4), (0, 2, -1), (-1, 0, 2), (-1, 2, -4), (0, 1, 2), (2, -1, -4), (-1, 0, -1), (0, 1, -4), (1, 2, -4), (-1, 0, 1), (-1, 1, 2), (0, 2, -4), (-1, 1, -1), (-1, 2, -1), (1, 2, -1), (0, 1, -1), (-1, 0, -4), (1, -1, -4)]
(-1, 0, 1)
和(0, 1, -1)
是具有相同组合的重复集合。我不确定如何克服这一点。
发布于 2019-04-30 08:25:42
如何获得组合,然后通过在字典中键入组合的frozenset
结果来只获取唯一的组合呢?在创建dictionary
之前,这将只使用生成器。
combs1, combs2 = itertools.tee(itertools.combinations(x, r=3))
res = list(dict(zip(map(frozenset, combs1), combs2)).values())
https://stackoverflow.com/questions/55912262
复制相似问题