簡體   English   中英

python 中所有可能的組合

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM