gpt4 book ai didi

python - 如何在 Python 中为列表中的多个分组生成排列

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:20 25 4
gpt4 key购买 nike

我知道我们可以使用 itertools.permutations 来排列列表中的不同项目,但是,如果我有一个列表,其中很少的项目需要处于固定位置,很少的项目需要与越来越少的项目交换需要再换2个吗?

例如:

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

如何使用 Python itertools.permutation 或其他方法生成具有以下约束的所有可能组合?

更新:

1 and 5 have fixed positions
In position 2, I could have either 6 or 11
In position 3, I could have either 2 or 12
In position 4, I could have 2 or 12
In position 6, I could have either 13, 14, 15 and so on

所以,我的列表如下所示:

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

我把数字放在了组里,代表同一组的数字可以互换。

谢谢。

最佳答案

你可以这样做:

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)

输出

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

更新

鉴于新的约束,你可以这样做:

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]

关于python - 如何在 Python 中为列表中的多个分组生成排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com