首页 > 解决方案 > 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' 的所有可能性

标签: pythonpython-3.x

解决方案


您可以使用来生成长度为 的itertools.product所有此类项目组合,然后使用每个组合压缩以进行输出:list2list1list1

[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')]]

推荐阅读