Reputation: 13
Create combinations of item attributes in order.
Hello, I am trying to create all the combinations of a product in a particular order. The actual problem is quite large, so I have simplified it here but with the same concept. First time using itertools.
Say I am selling a t-shirt. It comes in 3 sizes (s,m,l), 3 colours (w,b,g) and 2 fits (slim,baggy). Put together these make the product code, but have to be in the order of size-colour-fit.
So the combinations are:
S-W-SLIM
S-W-BAGGY
S-B-SLIM
S-B-BAGGY
etc.
My program would need to output all the codes, which should be 3x3x2 = 18 combinations.
import itertools
size = ['S','M','L']
colour = ['W','B','G']
fit = ['slim','baggy']
options = itertools.product(size, colour,fit,[3])
print (options)
<itertools.product object at 0x03718E68>
[Finished in 0.1s]
I have had a look at combinations() and permutations() but they only take 2 input arguments?
Unsure where to go from here, TIA.
Upvotes: 1
Views: 112
Reputation: 71620
Convert it to a list:
print(list(options))
Then it will output:
[('S', 'W', 'slim'), ('S', 'W', 'baggy'), ('S', 'B', 'slim'), ('S', 'B', 'baggy'), ('S', 'G', 'slim'), ('S', 'G', 'baggy'), ('M', 'W', 'slim'), ('M', 'W', 'baggy'), ('M', 'B', 'slim'), ('M', 'B', 'baggy'), ('M', 'G', 'slim'), ('M', 'G', 'baggy'), ('L', 'W', 'slim'), ('L', 'W', 'baggy'), ('L', 'B', 'slim'), ('L', 'B', 'baggy'), ('L', 'G', 'slim'), ('L', 'G', 'baggy')]
Also, you can skip the last argument of [3]
:
options = itertools.product(size, colour, fit)
It will output the same, you can check the length and it would be 18
.
If you need dashed between them:
options = ['-'.join(i) for i in itertools.product(size, colour, fit)]
And the output of:
print(options)
Would be:
['S-W-slim', 'S-W-baggy', 'S-B-slim', 'S-B-baggy', 'S-G-slim', 'S-G-baggy', 'M-W-slim', 'M-W-baggy', 'M-B-slim', 'M-B-baggy', 'M-G-slim', 'M-G-baggy', 'L-W-slim', 'L-W-baggy', 'L-B-slim', 'L-B-baggy', 'L-G-slim', 'L-G-baggy']
Upvotes: 1