当我找到一个lis的所有可能的组合时,我如何使它只有一些项目可以同时使用

2024-06-16 14:59:19 发布

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

很抱歉,这个标题很模糊,这是个很奇怪的问题。我使用此代码查找列表中所有可能的组合:

from itertools import chain, combinations
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


stuff = ['pretzel', 'sesame', 'sourdough', 'donut', 'waffles', 'beef', 'turkey', 'chicken', 'tuna', 'vegan', 'pork', 'steak', 'bison', 'cheese', 'kethcup', 'mayo', 'pickles', 'mustard', 'lettuce', 'onions', 'tomato', 'bacon', 'bbq', 'hotsauce', 'pb', 'jelly', 'butter', 'jalapeno', 'frenchfry', 'apple', 'honeymustard', 'onionrings', 'ranch', 'macncheese', 'pulledpork', 'avacado', 'mushrooms']
for i, combo in enumerate(powerset(stuff), 1):
    print('combo #{}: {}'.format(i, combo))

老实说,这是我在Google上找到的第一个代码,它几乎实现了我想要的。它吐出所有可能的组合,甚至给每一个数字! 然而,我需要它做的事情已经改变了,我真的不知道该做什么(这并不是说太多),所以我来这里问:我要怎么做才能让列表中的一些项目可以一起使用?例如,我不想把面包或肉的种类列在一起,但调味品可以用任何组合(或缺少组合)。提前谢谢

编辑:我最终要做的是找到并列出一个三明治上所有可能的面包、肉和调味品的组合。给定选项中的面包和肉类型只能使用一次,但任何调味品的任何组合都是可以接受的(因此使用它们都是一个选项)


Tags: 代码infrom标题chain列表for选项
1条回答
网友
1楼 · 发布于 2024-06-16 14:59:19

你可以做:

def subsets(l):
   ret = []
   for n in range(len(l)+1):
       ret += list(itertools.combinations(l, n))
   return ret

buns = ["sesame", "sourdough"]
meat = ["ham" , "beef"]
condiments = ["ketchup","mustard", "onions"] 
combo = []
for b in buns:
   for m in meat:
       for c in subsets(condiments):
            x = [b,m]
            for s in c:
                x.append(s)
            combo.append(x)

组合框将包含所有可能的答案

相关问题 更多 >