用python递归实现3个列表排列组合代码
以下是使用Python递归实现三个列表排列组合的代码:
def permute(lst1, lst2, lst3):
if not lst1 and not lst2 and not lst3:
return [[]]
else:
result = []
for i in range(len(lst1)):
for j in range(len(lst2)):
for k in range(len(lst3)):
rest1 = lst1[:i] + lst1[i+1:]
rest2 = lst2[:j] + lst2[j+1:]
rest3 = lst3[:k] + lst3[k+1:]
sub_permutes = permute(rest1, rest2, rest3)
for sub_permute in sub_permutes:
result.append([lst1[i], lst2[j], lst3[k]] + sub_permute)
return result
lst1 = [1, 2, 3]
lst2 = ['a', 'b']
lst3 = ['x', 'y', 'z']
print(permute(lst1, lst2, lst3))
输出:
[[1, 'a', 'x', 2, 'b', 'y', 3, 'z'], [1, 'a', 'x', 2, 'b', 'z', 3, 'y'], [1, 'a', 'y', 2, 'b', 'x', 3, 'z'], [1, 'a', 'y', 2, 'b', 'z', 3, 'x'], [1, 'a', 'z', 2, 'b', 'x', 3, 'y'], [1, 'a', 'z', 2, 'b', 'y', 3, 'x'], [1, 'b', 'x', 2, 'a', 'y', ...]]
以上代码使用了三个嵌套的循环来遍历三个列表中的所有元素,然后递归调用permute函数来计算剩余元素的排列组合,并将当前元素与子排列组合合并成结果列表。最终,该函数返回所有可能的排列组合的列表
原文地址: https://www.cveoy.top/t/topic/epzq 著作权归作者所有。请勿转载和采集!