【发布时间】:2019-04-30 00:04:33
【问题描述】:
我有一组数字[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) 是具有相同组合的重复集。我不确定如何克服这个问题。
【问题讨论】:
标签: python combinations permutation itertools