![](/img/trans.png)
[英]How do I get all possible item combinations from two tables when some items have the same ID value?
[英]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.