Python3列表理解从列表中删除元组

2024-09-27 00:22:13 发布

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

我必须为大学解决一项任务。我有4个给定的列表,我必须计算在某些限制条件下可以制作的汉堡的可能变化

breads = ["Weissbrot", "Vollkorn", "Dinkel", "Speckbrot"]
patties = ["Wildschwein", "Rind", "Halloumi", "Aubergine"]
souces = ["Kaese", "Knoblauch", "Curry"]
toppings = ["Kopfsalat", "Bacon", "Tomate"]

到目前为止,我的代码是:

i = "bottom, patty, souce, topping, top"

burger = [i for bottom in breads
          for top in breads
          for patty in patties
          for souce in souces
          for topping in toppings
          if bottom != top
          if i != ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")]

print(len(burger))

限制:

成品汉堡需要有结构(底部、肉饼、馅饼、顶部、顶部)。我把它保存在变量“I”下。底部和顶部必须有不同的面包。我用if bottom != top解决了这个问题

不允许将茄子与腌肉、卡萨或培根混合,哈卢米与腌肉或培根混合。我试图用if i != ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")来解决这个问题,但它显然是不正确的

此外,如果底部和顶部互换,其余部分保持不变,则这算作1个汉堡,而不是2个汉堡。我还没有解决这个问题的计划

对不起,德语单词,如果需要我可以翻译

非常感谢

编辑:正确答案是138个变体


Tags: inforiftopbacontoppingsbottompatty
3条回答

您的问题在于变量i,它的工作方式与您希望的不一样。它不能代替命名五个变量。它只是一个字符串,碰巧包含变量名

这将是一个有效的理解,尽管我怀疑最后一个if子句的限制比您想要的要窄得多(它只禁止一个组合)

burger = [(bottom, patty, souce, topping, top)
          for bottom in breads
          for top in breads
          for patty in patties
          for souce in souces
          for topping in toppings
          if bottom != top
          if (bottom, patty, souce, topping, top) !=
             ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot")]

使用列表理解,这是有效的

choices = [[b, p, s, t] for b in breads for p in patties for s in souces for t in toppings] #add restrections (if [b,p, s, t] !=)

打印(选项)

首先,在这种情况下,您可能不应该使用列表理解。列表理解只适用于较小的事情,这太混乱了。这可能是最好的方法(使用for循环)。在下面的代码中,count将是总数,所有选择都是可能的汉堡

choices = []
count = 0
for b in breads:
    for p in patties:
        for s in souces:
            for t in toppings:
                temp = [b, p, s, t]
                #add restrictions here
                choices.append(temp)
                count += 1

打印(选项、计数)

相关问题 更多 >

    热门问题