簡體   English   中英

我將如何做到這一點,以便在查找列表的所有可能組合時只能同時使用某些項目

[英]How would I make it so only some items are able to be used at the same time when finding all possible combinations of a list

很抱歉,標題不夠描述,這是一個非常奇怪的問題。 我正在使用此代碼查找列表的所有可能組合:

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 上找到的第一個代碼塊,幾乎可以滿足我的需求。 它吐出所有可能的組合,甚至給每個組合一個數字! 然而,我需要它做的事情已經改變,我真的不知道該怎么做(這並不是說太多),所以我來這里問:我如何做到只有一些該列表中的項目可以一起使用嗎? 例如,我不希望包子或肉的類型能夠一起列出,但調味品可以任意組合使用(或缺少組合)。 提前致謝。

編輯:我最終想要完成的是,我需要在給定的三明治上找到並列出面包、肉和調味品的所有可能組合。 給定選項中的面包和肉類類型只能使用一次,但任何調味品的任何組合都是可以接受的(因此全部使用它們是一種選擇)。

你可以這樣做:

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)

組合將包含所有可能的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM