如何生成输入列表全排列的有序可重组合?
问题解决:生成全排列的有序可重组合
给定输入列表如[1,2],需生成该列表所有全排列的有序可重组合,组合长度与原列表长度一致,期望输出为:
[[[1,2],[1,2]],[[1,2],[2,1]],[[2,1],[1,2]],[[2,1],[2,1]]]
但你提供的代码返回结果缺失了[[2,1],[1,2]]:
from itertools import permutations, combinations_with_replacement def generate_preferences(input_list): n = len(input_list) all_permutations = [list(p) for p in list(permutations(input_list, n))] all_combinations = [list(p) for p in list(combinations_with_replacement(all_permutations, n))] return all_combinations
当前返回结果:
[[[1,2],[1,2]],[[1,2],[2,1]],[[2,1],[2,1]]]
问题原因
combinations_with_replacement生成的是无顺序的可重组合,它会忽略元素的排列顺序,将([2,1], [1,2])和([1,2], [2,1])视为同一种组合,只保留其中一个,这就是目标项缺失的核心原因。
修正方案
要生成有序的可重组合,需要使用itertools.product,它会生成输入序列的笛卡尔积,包含所有顺序不同的组合情况:
from itertools import permutations, product def generate_preferences(input_list): n = len(input_list) all_permutations = [list(p) for p in permutations(input_list, n)] # 使用product生成有序可重组合,repeat参数指定组合长度 all_combinations = [list(p) for p in product(all_permutations, repeat=n)] return all_combinations
验证结果
调用generate_preferences([1,2])会返回完整的期望结果:
[[[1,2],[1,2]],[[1,2],[2,1]],[[2,1],[1,2]],[[2,1],[2,1]]]
内容的提问来源于stack exchange,提问作者rithvik
相关产品推荐
相关产品推荐

