[英]All possible combinations in python
我正在寻找 python 中针对此问题的所有可能组合:
list1 = ['M','W','D']
list2 = ['y','n']
我想要的是:
[[('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')]]
这绝对不是我想要的,因为我需要将 list1 的所有元素显示到同一个列表中并与 list2 的元素组合。
我不确定列表是否适合这个问题,但我需要的是 'D'、'W'、'M' 和 'y'、'n' 的所有可能性
您可以使用itertools.product
生成list2
长度为list1
的所有此类组合,然后使用 zip list1
生成 output 的每个组合:
[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')]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.