gpt4 book ai didi

python - 如何从所有排列生成所有可能的组合?

转载 作者:行者123 更新时间:2023-11-28 21:10:58 25 4
gpt4 key购买 nike

我有一个 Python 中 K 元素的所有排列列表,如下所示:

import itertools
perms = list(itertools.permutations(range(K), K))

我想生成这些排列 perms 所有可能组合的矩阵(或列表)M。此矩阵(或列表)的每个元素的大小为 N。我该怎么做?

例如,对于 K=2,我会得到 perms=[(0, 1), (1, 0)]。对于 N=3,我想要:

M = [ [(0, 1), (0, 1), (0, 1)],
[(0, 1), (0, 1), (1, 0)],
[(0, 1), (1, 0), (0, 1)],
[(0, 1), (1, 0), (1, 0)],
[(1, 0), (0, 1), (0, 1)],
[(1, 0), (0, 1), (1, 0)],
[(1, 0), (1, 0), (0, 1)],
[(1, 0), (1, 0), (1, 0)] ]

M 是一个包含 8 个列表的列表。每个列表的大小为 N=3 并包含来自 perms 的元素。

对于N=2,我想要:

M = [ [(0, 1), (0, 1)],
[(0, 1), (1, 0)],
[(1, 0), (0, 1)],
[(1, 0), (1, 0)] ]

对于 N=1,我希望:

M = [ [(0, 1), (1, 0)] ] = perms

我不知道我是否正确地表述了我的问题(我认为它可以比这更清楚地重新表述)。

最佳答案

您可以使用 itertools 中的 product

from itertools import permutations, product

perms = permutations(range(2))
cartesian_tuples = product(perms, repeat=3)

# (((0, 1), (0, 1), (0, 1)),
# ((0, 1), (0, 1), (1, 0)),
# ((0, 1), (1, 0), (0, 1)),
# ((0, 1), (1, 0), (1, 0)),
# ((1, 0), (0, 1), (0, 1)),
# ((1, 0), (0, 1), (1, 0)),
# ((1, 0), (1, 0), (0, 1)),
# ((1, 0), (1, 0), (1, 0)))

如果您需要多次迭代任何内容,您可以手动将各个部分转换为列表。当前结构由生成器组成,生成器将在一次迭代后耗尽,无法再次使用。如果你想要嵌套列表:

cartesian_tuples = map(list, list(product(perms, repeat=3)))

# [[(0, 1), (0, 1), (0, 1)],
# [(0, 1), (0, 1), (1, 0)],
# [(0, 1), (1, 0), (0, 1)],
# [(0, 1), (1, 0), (1, 0)],
# [(1, 0), (0, 1), (0, 1)],
# [(1, 0), (0, 1), (1, 0)],
# [(1, 0), (1, 0), (0, 1)],
# [(1, 0), (1, 0), (1, 0)]]

在 Python 3.X 中,您必须将其包装在另一个 列表调用中,因为map(...) 返回一个map对象。

cartesian_tuples = list(map(list, list(product(perms, repeat=3))))

或者,您可以避免所有这些废话并使用列表理解。

cartesian_tuples = [[perm for perm in prod] for prod in product(perms, repeat=3)]

但每次需要时都创建一个新的迭代器可能会更好。

def product_of_permutations(n, k):
return product(permutations(range(k)), repeat=n)

关于python - 如何从所有排列生成所有可能的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35948907/

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