生成两个相同列表的所有组合的脚本可以使用递归的方式来实现。下面是一个示例的Python脚本:
def generate_combinations(list1, list2, prefix=[]):
if len(list1) == 0 and len(list2) == 0:
print(prefix)
return
if len(list1) > 0:
generate_combinations(list1[1:], list2, prefix + [list1[0]])
if len(list2) > 0:
generate_combinations(list1, list2[1:], prefix + [list2[0]])
list1 = [1, 2, 3]
list2 = [4, 5]
generate_combinations(list1, list2)
这个脚本会输出两个列表的所有组合,例如对于输入的list1 = [1, 2, 3]
和list2 = [4, 5]
,输出结果为:
[1, 2, 3, 4, 5]
[1, 2, 3, 5, 4]
[1, 2, 4, 3, 5]
[1, 2, 4, 5, 3]
[1, 2, 5, 3, 4]
[1, 2, 5, 4, 3]
[1, 4, 2, 3, 5]
[1, 4, 2, 5, 3]
[1, 4, 3, 2, 5]
[1, 4, 3, 5, 2]
[1, 4, 5, 2, 3]
[1, 4, 5, 3, 2]
[1, 5, 2, 3, 4]
[1, 5, 2, 4, 3]
[1, 5, 3, 2, 4]
[1, 5, 3, 4, 2]
[1, 5, 4, 2, 3]
[1, 5, 4, 3, 2]
[2, 1, 3, 4, 5]
[2, 1, 3, 5, 4]
[2, 1, 4, 3, 5]
[2, 1, 4, 5, 3]
[2, 1, 5, 3, 4]
[2, 1, 5, 4, 3]
[2, 3, 1, 4, 5]
[2, 3, 1, 5, 4]
[2, 3, 4, 1, 5]
[2, 3, 4, 5, 1]
[2, 3, 5, 1, 4]
[2, 3, 5, 4, 1]
[2, 4, 1, 3, 5]
[2, 4, 1, 5, 3]
[2, 4, 3, 1, 5]
[2, 4, 3, 5, 1]
[2, 4, 5, 1, 3]
[2, 4, 5, 3, 1]
[2, 5, 1, 3, 4]
[2, 5, 1, 4, 3]
[2, 5, 3, 1, 4]
[2, 5, 3, 4, 1]
[2, 5, 4, 1, 3]
[2, 5, 4, 3, 1]
[3, 1, 2, 4, 5]
[3, 1, 2, 5, 4]
[3, 1, 4, 2, 5]
[3, 1, 4, 5, 2]
[3, 1, 5, 2, 4]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
[5, 4, 2, 3, 1]
[5, 4, 3, 1, 2]
[5, 4, 3, 2, 1]
这个脚本会生成两个列表的所有可能组合,并将结果打印出来。注意,这个脚本的时间复杂度为O(2^n),其中n为两个列表的长度之和。
领取专属 10元无门槛券
手把手带您无忧上云