如何用Python工具/库实现多列表的全排列组合匹配需求
问题
现有三个长度相同的列表:
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)] ... 以此类推
曾尝试使用itertools的combinations、permutations、product方法,但仅能解决部分需求;自行实现递归函数可解决问题,现询问是否有更便捷的工具或库可快速实现该需求。
解决方案
可以直接用itertools的permutations和product组合实现,无需自行编写递归。核心逻辑如下:
- 对
list1生成所有排列(对应元组第一个元素的任意顺序) - 对
list3生成所有排列(对应元组第三个元素的任意顺序) - 用
product获取两组排列的所有配对,再将每对排列与list2按位置组合成目标结构
具体代码示例:
import itertools list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] list3 = ['A', 'B', 'C'] # 生成list1和list3的所有排列 perm_list1 = itertools.permutations(list1) perm_list3 = itertools.permutations(list3) # 遍历所有排列配对,生成目标组合 for idx, (p1, p3) in enumerate(itertools.product(perm_list1, perm_list3), start=1): combination = list(zip(p1, list2, p3)) print(f"combination {idx}: {combination}")
这段代码会输出全部36种符合要求的组合(3! * 3! = 36),完全覆盖需求场景。
如果需要list2的元素也参与排列(即元组第二个元素也可打乱顺序),只需新增list2的排列生成,再将三组排列做笛卡尔积:
perm_list2 = itertools.permutations(list2) for idx, (p1, p2, p3) in enumerate(itertools.product(perm_list1, perm_list2, perm_list3), start=1): combination = list(zip(p1, p2, p3)) print(f"combination {idx}: {combination}")
内容的提问来源于stack exchange,提问作者Jobo Fernandez
相关产品推荐
相关产品推荐

