【问题标题】:Return all possible combinations of two lists返回两个列表的所有可能组合
【发布时间】:2022-01-12 17:47:30
【问题描述】:

我尝试使用 class 返回两个给定列表的所有可能组合,该组合必须由每个列表中的一个元素组成。我可以做到直到第二个列表的长度为 1。但是增加长度后,我没有得到预期的输出。

以代码为例

class IceCreamMachine:

    def __init__(self, ingredients, toppings):
        self.ingredients = ingredients
        self.toppings = toppings
        
    def scoops(self):
        IceCreamList = []
        for i in range(len(self.ingredients)):
            IceCreamList.append([self.ingredients[i], self.toppings[i%len(self.toppings)]])
        
        return IceCreamList
        
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])

print(machine.scoops())

它返回预期的输出 [['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']] 但每当我倾向于增加第二个列表显示了一个不正确的答案。 谁能建议我如何解决这个问题?

【问题讨论】:

  • 使用itertools.product
  • 假设你在d = [["vanilla", "chocolate"], ["chocolate sauce"]] 中有列表,你可以使用像@chepner 说的print(list(product(*d))) 这样的itertools 这会给你[('vanilla', 'chocolate sauce'), ('chocolate', 'chocolate sauce')]

标签: python list class oop combinations


【解决方案1】:

使用itertools.product

import itertools

class IceCreamMachine:
    def __init__(self, ingredients, toppings):
        self.ingredients = ingredients
        self.toppings = toppings
        
    def scoops(self):
      return list(itertools.product(self.ingredients,self.toppings))
        
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce","banana sauce"])
print(machine.scoops())

输出

[('vanilla', 'chocolate sauce'), ('vanilla', 'banana sauce'), ('chocolate', 'chocolate sauce'), ('chocolate', 'banana sauce')]

【讨论】:

    【解决方案2】:

    我认为这可以通过使用两个for循环来完成:

    def scoops(self):
        IceCreamList = []
        for i in range(len(self.ingredients)):
            for j in range(len(self.toppings)):
                IceCreamList.append([self.ingredients[i], self.toppings[j]])
        
        return IceCreamList
    

    使用“for [variable] in [list]”可以使代码看起来更简单

    def scoops(self):
        IceCreamList = []
        for i in self.ingredients:
            for j in self.toppings:
                IceCreamList.append([i,j])
        
        return IceCreamList
    

    如果你想有多个选项的组合,那么代码会更复杂...

    【讨论】:

    • 非常感谢❤它完美运行............!!
    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多