简体   繁体   中英

All possible combinations in python

I'm looking to find all the possible combinations in python for this problem:

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'), ....

i need to have all the possibilities for M,W,D like this:

M W D

y n y

y y y

y y n

y n n

n y y

n n y

. . .

I tried:

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)

and i get:

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

And it's absolutely not what i'm looking for as i need all the element of the list1 to be displayed into the same list and combined with the element of the list2.

I'm not sure if lists are appropriates for this problem, but what i need is all the possibilities for 'D', 'W', 'M' with 'y','n'

You can use itertools.product to produce all such combinations of list2 items with the length of list1 , and then zip list1 with each combination for output:

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

This returns:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM