我正在拼命尝试获取列表的所有排列,同时强制执行位置分配约束。 我有一个列表[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
答案 0 :(得分:2)
过滤这些子集的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)]