所以我100%不熟悉编程,虽然我是一个学习速度非常快的学生,但我需要帮助。
我想在Python上找到使用多个列表的所有可能组合。我知道它有一个intertool,但老实说,我甚至不知道从哪里开始,如何使用它,甚至不知道如何输入我的数据。
我尝试做的一个基本示例:
Flavors Sizes Toppings Syrups
========== ======= ============= ==============
Chocolate Small Sprinkles Hot fudge
Vanilla Medium Gummy bears Caramel
Strawberry Large Oreo Strawberry
Coffee Cookie dough White chocolate
Snickers etc.
Brownies
etc.
因此,对于口味和大小,只能有一个选择,但让我们说糖浆,我让他们选择三种选择,对于浇头我也让他们选择三种。我想找到所有组合。
这很难吗?我需要什么样的代码以及如何输入我的变量?
感谢。非常感谢。
P.s.- python可以采用多少组合?普通macbook pro的cpu能用多少钱?
答案 0 :(得分:5)
我认为您正在寻找的是product
:
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
result = list(itertools.product(a1,a2,a3))
>>> print result
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]
答案 1 :(得分:1)
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.
答案 2 :(得分:0)
from itertools import product, combinations, combinations_with_replacement
flavors = ["chocolate", "vanilla", "strawberry", "coffee"]
sizes = ["small", "medium", "large"]
syrups = ["hot fudge", "caramel", "strawberry", "white chocolate"]
toppings = ["sprinkles", "gummy bears", "oreos", "cookie dough", "snickers", "brownies"]
all_combos = list(
product(flavors, sizes, combinations(syrups, 3), combinations(toppings, 3))
)