python使用多个列表查找所有组合。完成编程新手

2024-10-01 15:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对编程是100%的新手,虽然我对大多数事情都学得很快,但我需要帮助。在

我想在Python上使用多个列表查找所有可能的组合。我知道它有一个工具,但老实说,我甚至不知道从哪里开始,如何使用它,甚至不知道如何输入我的数据。在

我想做的一个基本例子是:

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.

所以对于口味和大小只能有一个选择,但是假设糖浆我让他们选三个,而对于配料我也让他们选三个。我想找到所有的组合。在

这很难做到吗?我需要的确切代码是什么?如何准确地输入变量?在

谢谢。非常感谢。在

另外,python可以接受多少个组合有限制吗?一台普通的MacBookPro的cpu能用多少?在


Tags: 工具数据列表编程etc事情老实例子
3条回答
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))
)
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]))

输出看起来像

^{pr2}$

编辑:

需要指出的另一件事是,这假设了浇头的顺序并不重要-即["sprinkles", "oreos", "cookie dough"]实际上与["oreos", "sprinkles", "cookie dough"]完全相同。在

如果顺序很重要,则需要查看itertools.permutations(toppings, 3)(不允许每个都超过一个)或{}(允许倍数)。在

请注意,考虑顺序会大大增加组合的数量—在本例中从4800增加到92160。在

我想你要找的是product

Example:

导入itertools

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)]

相关问题 更多 >

    热门问题