python中所有可能的组合

las*_*nce 4 python python-3.x

我正在寻找 python 中针对此问题的所有可能组合:

list1 = ['M','W','D']
list2 = ['y','n']
Run Code Online (Sandbox Code Playgroud)

我想要的是:

[[('M', 'y'), ('W', 'n'), ('D', 'n')], [('M', 'y'), ('D', 'n'), ('W', 'n'), ....
Run Code Online (Sandbox Code Playgroud)

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

M W D

y n y

y y y

y y n

y n n

n y y

n n y

. . .
Run Code Online (Sandbox Code Playgroud)

我试过:

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)
Run Code Online (Sandbox Code Playgroud)

我得到:

[[('M', 'y'), ('W', 'n')], [('M', 'y'), ('D', 'n')], [('W', 'y'), ('M', 'n')], [('W', 'y'), ('D', 'n')], [('D', 'y'), ('M', 'n')], [('D', 'y'), ('W', 'n')]]
Run Code Online (Sandbox Code Playgroud)

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

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

blh*_*ing 8

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

[list(zip(list1, c)) for c in itertools.product(list2, repeat=len(list1))]
Run Code Online (Sandbox Code Playgroud)

这将返回:

[[('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')]]
Run Code Online (Sandbox Code Playgroud)

  • 当您发布时,刚刚写完该解决方案...好吧,那就是+1:) (3认同)
  • 你不是一个人。;) (3认同)