from itertools import product, combinations, combinations_with_replacement
flavors = ["chocolate", "vanilla", "strawberry", "coffee"]
sizes = ["small", "medium", "large"]
toppings = ["sprinkles", "gummy bears", "oreos", "cookie dough", "snickers", "brownies"]
syrups = ["hot fudge", "caramel", "strawberry", "white chocolate"]
#
# pick a flavor and a size
for flavor,size in product(flavors, sizes):
#
# pick three toppings, but no more than one of each
for top_a, top_b, top_c in combinations(toppings, 3):
#
# pick three syrups, allowing repeats
for syr_a, syr_b, syr_c in combinations_with_replacement(syrups, 3):
#
# now do something with the result:
print(", ".join([flavor, size, top_a, top_b, top_c, syr_a, syr_b, syr_c]))
和输出看起来像
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, hot fudge, hot fudge
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, hot fudge, caramel
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, hot fudge, strawberry
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, hot fudge, white chocolate
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, caramel, caramel
chocolate, small, sprinkles, gummy bears, oreos, hot fudge, caramel, strawberry
# ... etc
# (4800 combinations in total)
编辑:
要指出的另一件事是,这假定浇头的顺序并不重要——即["sprinkles", "oreos", "cookie dough"]
实际上与["oreos", "sprinkles", "cookie dough"]
.
如果顺序很重要,您需要查看itertools.permutations(toppings, 3)
(不允许每个超过一个)或itertools.product(toppings, repeat=3)
(允许多个)。
请注意,考虑顺序会大大增加组合的数量——在本例中从 4800 增加到 92160。