【发布时间】: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