用Python实现穷举组合

编程语言 2026-07-09

设想我有3 个列表:

list1 = a, b, c

list2 = 1, 2, 3

list3 = A, B, C

我想要的结果类似于:

combination 1: [(a, 1, A), (b, 2, B), (c, 3, C)]

combination 2: [(a, 1, A), (b, 2, C), (c, 3, B)]

combination 3: [(a, 1, B), (b, 2, C), (c, 3, A)]

combination 4: [(a, 1, B), (b, 2, A), (c, 3, C)]

combination 5: [(a, 1, C), (b, 2, A), (c, 3, B)]

combination 6: [(a, 1, C), (b, 2, B), (c, 3, A)]

combination 7: [(b, 1, A), (a, 2, B), (c, 3, C)]

... and so on

我已经使用过itertools的组合、排列和/或乘积,但它只能解决整个问题的一部分。我之前也尝试实现一个递归函数来解决这个问题,虽然它能工作,但我只是想知道是否有更高效的工具或库可以更快地解决这个问题。

附言:我不太确定该如何给这个问题起标题,抱歉。

解决方案

期望的组合对我来说看起来像排列的笛卡尔积
并且它需要 zip() 来把值整理成正确的元组。

这似乎给出了期望的值

import itertools

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = ["A", "B", "C"]

per1 = itertools.permutations(list1)
per2 = itertools.permutations(list2)
per3 = itertools.permutations(list3)

prod = itertools.product(per1, per2, per3)

result = (list(zip(*items)) for items in prod)

for item in result:
    print(item)

结果:

[('a', 1, 'A'), ('b', 2, 'B'), ('c', 3, 'C')]
[('a', 1, 'A'), ('b', 2, 'C'), ('c', 3, 'B')]
[('a', 1, 'B'), ('b', 2, 'A'), ('c', 3, 'C')]
[('a', 1, 'B'), ('b', 2, 'C'), ('c', 3, 'A')]

# ...

[('c', 3, 'B'), ('b', 2, 'A'), ('a', 1, 'C')]
[('c', 3, 'B'), ('b', 2, 'C'), ('a', 1, 'A')]
[('c', 3, 'C'), ('b', 2, 'A'), ('a', 1, 'B')]
[('c', 3, 'C'), ('b', 2, 'B'), ('a', 1, 'A')]
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章