具有约束条件的列表排列 python

Permutations of a list with constraints python

我在强制执行位置分配约束的同时拼命地尝试获取列表的所有排列。 我有一个列表 [1,2,3,4,5,6](6 只是一个例子,我想找到可以适用于每个长度的东西)我想找到所有长度为 3 的列表(也示例)具有以下约束:

这将给出这些列表:[1,2,3],[1,2,4],[1,3,2],[1,3,4],[2 ,1,3],[2,3,4],[2,1,4]

For those interested, what I am trying to implement is what is explained pages 5 and 6 of this paper

过滤这些子集的 product()

from itertools import product

for combo in product([1, 2], [1, 2, 3], [2, 3, 4]):
    if len(set(combo)) == 3:
        print(combo)

或作为列表理解:

[combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]

输出:

>>> from itertools import product
>>> [combo for combo in product([1, 2], [1, 2, 3], [2, 3, 4]) if len(set(combo)) == 3]
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (2, 1, 3), (2, 1, 4), (2, 3, 4)]