Python中的所有可能组合

4

我正在寻找在Python中解决此问题的所有可能组合:

list1 = ['M','W','D']
list2 = ['y','n']

What i'm looking to have is:

[[('M', 'y'), ('W', 'n'), ('D', 'n')], [('M', 'y'), ('D', 'n'), ('W', 'n'), ....

我需要像这样拥有M、W、D的所有可能性:
M W D

y n y

y y y

y y n

y n n

n y y

n n y

. . .

我尝试了:

import itertools
list1 = ['M','W','D']
list2 = ['y','n']
all_combinations = []
list1_permutations = itertools.permutations(list1, len(list2))
for each_permutation in list1_permutations:
    zipped = zip(each_permutation, list2)
    all_combinations.append(list(zipped))
print(all_combinations)

我得到:

[[('M', 'y'), ('W', 'n')], [('M', 'y'), ('D', 'n')], [('W', 'y'), ('M', 'n')], [('W', 'y'), ('D', 'n')], [('D', 'y'), ('M', 'n')], [('D', 'y'), ('W', 'n')]]

这绝对不是我所需要的,因为我需要将列表1的所有元素显示在同一个列表中,并与列表2的元素组合。

我不确定列表是否适用于此问题,但我需要' D'、' W'、' M'和' y'、' n'的所有可能性。


你的示例中前两个元素相同,只是顺序不同。这真的很重要吗?根据你的表格示例,顺序似乎并不重要。 - Tomerikoo
1个回答

8

你可以使用itertools.product来生成所有由list2中的元素组成且长度为list1的组合,然后将list1与每个组合一起进行zip操作以输出:

[list(zip(list1, c)) for c in itertools.product(list2, repeat=len(list1))]

这将返回:

[[('M', 'y'), ('W', 'y'), ('D', 'y')],
 [('M', 'y'), ('W', 'y'), ('D', 'n')],
 [('M', 'y'), ('W', 'n'), ('D', 'y')],
 [('M', 'y'), ('W', 'n'), ('D', 'n')],
 [('M', 'n'), ('W', 'y'), ('D', 'y')],
 [('M', 'n'), ('W', 'y'), ('D', 'n')],
 [('M', 'n'), ('W', 'n'), ('D', 'y')],
 [('M', 'n'), ('W', 'n'), ('D', 'n')]]

3
刚刚写完这个解决方案,就看到你发布了...好的,那就点赞+1 :) - Tomerikoo
3
你不是孤单的。 ;) - Matthias
1
我正准备回答,但是看到了你的回答。+1 - Pygirl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接