我在Python中有一个原始列表,如下所示:
list = [a, 1, b, 2, c, 3]
我将其分为以下两个列表:
list_1 = [a, b, c]
list_2 = [1, 2, 3]
我想找到的是列表的最终列表,该列表为我提供了list_1
和list_2
的所有可能组合,无需将其当前的“柱”。因此输出应如下所示:
所需的输出:
final_list =[[a, b, c],
[a, 2, c],
[a, b, 3],
[a, 2, 3],
[1, b, c],
[1, 2, c],
[1, b, 3],
[1, 2, 3]]
有什么想法可以实现这一目标吗?
答案 0 :(得分:3)
这是一种蛮力递归方法:
def get_combinations(curr_list, list1, list2, index, overall_list):
if index == len(list1) or index == len(list2):
overall_list.append(curr_list[:])
return
curr_list[index] = list1[index]
get_combinations(curr_list, list1, list2, index+1, overall_list)
curr_list[index] = list2[index]
get_combinations(curr_list, list1, list2, index+1, overall_list)
list1 = list(input().strip().split())
list2 = list(input().strip().split())
overall_list = []
curr_list = [None] * min(len(list1), len(list2))
get_combinations(curr_list, list1, list2, 0, overall_list)
for l in overall_list:
print(*l)
输入:
a b c
1 2 3
输出:
a b c
a b 3
a 2 c
a 2 3
1 b c
1 b 3
1 2 c
1 2 3
答案 1 :(得分:0)
我认为这样看待您的问题会更容易:
list = [a, 1, b, 2, c, 3]
制作三个列表,一个表示第一个数字可取的值,一个表示第二个,第三个表示的值:
first = [a,1]
second = [b,2]
third = [c,3]
要生成每种组合,可以组合三个for循环,以循环访问三个列表的元素。在哪个for循环中使用哪个列表更改组合生成的顺序。我使我的示例与您的输出匹配:
for f in first:
for t in third:
for s in second:
//Here you have a [f,s,t] combination