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')]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With