如何在Python中为列表中的多个分组生成置换

2024-05-15 04:53:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我们可以利用itertools.排列然而,为了在一个列表中排列不同的项目,如果我有一个列表,使得一些项目需要在固定的位置上,很少的项目需要与一个项目交换,而很少的项目需要与另外两个项目交换呢?在

例如:

test = [1, 6, 2, 12, 5, 13, 11, 14, 15]

如何使用Pythonitertools.排列或者用另一种方法来生成所有可能的组合,并具有以下约束条件?在

更新:

^{pr2}$

所以,我的清单如下:

[1, (6, 11), (2, 12), (2,12), 5, (13, 14, 15), (6, 11), (13, 14, 15), (13, 14, 15)]

我把这些数字包括在组中,表示同一组中的数字可以相互交换。在

谢谢。在


Tags: 项目方法test利用列表数字itertools约束条件
1条回答
网友
1楼 · 发布于 2024-05-15 04:53:38

你可以这样做:

from itertools import permutations, product, chain

test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
groups = [[1], [2, 3, 4], [5], [6, 7], [8, 9], [10], [11, 12, 13], [14], [15, 16]]

result = [list(chain.from_iterable(permutation)) for permutation in product(*map(permutations, groups))]

for e in result[:20]:
    print(e)

输出

^{pr2}$

更新

考虑到新的约束条件,您可以这样做:

from functools import partial
from itertools import combinations, permutations, product, chain

choose_one = partial(lambda r, iterable: combinations(iterable, r), 1)
groups = [[[1]], combinations([6, 11], 1), permutations([2, 12]), [[5]], combinations([13, 14, 15], 1)]

for e in product(*groups, repeat=1):
    print(list(chain.from_iterable(e)))

输出

[1, 6, 2, 12, 5, 13]
[1, 6, 2, 12, 5, 14]
[1, 6, 2, 12, 5, 15]
[1, 6, 12, 2, 5, 13]
[1, 6, 12, 2, 5, 14]
[1, 6, 12, 2, 5, 15]
[1, 11, 2, 12, 5, 13]
[1, 11, 2, 12, 5, 14]
[1, 11, 2, 12, 5, 15]
[1, 11, 12, 2, 5, 13]
[1, 11, 12, 2, 5, 14]
[1, 11, 12, 2, 5, 15]

相关问题 更多 >

    热门问题