【问题标题】:Python 3 List Comprehension remove tuples from listPython 3 列表理解从列表中删除元组
【发布时间】:2020-06-29 02:03:03
【问题描述】:

我必须解决大学的任务。我有 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解决了这个问题。

不允许将茄子与 Speckbrot、Kaese 或培根以及 Halloumi 与 Speckbrot 或培根混合。我试图用if i != ("Speckbrot", "Aubergine", "Kaese", "Bacon", "Weissbrot") 解决这个问题,但它显然不正确。

此外,如果底部和顶部被交换并且其余部分保持不变,这将被视为 1 个汉堡而不是 2 个。我还没有计划如何解决这个问题。

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

在此先感谢

编辑:正确答案是 138 种变体。

【问题讨论】:

    标签: python list list-comprehension


    【解决方案1】:

    您的问题在于变量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")]
    

    【讨论】:

    • 我添加了if (bottom, patty) != ("Speckbrot", "Aubergine") if (top, patty) != ("Speckbrot", "Aubergine") if (patty, souce) != ("Aubergine", "Kaese") if (patty, topping) != ("Aubergine", "Bacon") if (patty, bottom) != ("Halloumi", "Speckbrot") if (patty, top) != ("Halloumi", "Speckbrot") if (patty, topping) != ("Halloumi", "Bacon"),它有效,但有更好的方法吗?
    • 您也许可以将一些条件与布尔代数结合起来(例如and 表达式),但它可能并不容易或更简洁。通常你不会在一个语句中做这样复杂的事情。
    • 好的,非常感谢。您知道如何实施最后一个限制吗?
    【解决方案2】:

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

    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
    

    打印(选择,计数)

    【讨论】:

    • 不幸的是,我必须使用列表理解。
    【解决方案3】:

    使用列表推导,这是可行的

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

    打印(选择)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多