[英]Return all possible combinations of two lists
我尝试使用class返回两个给定列表的所有可能组合,该组合必须由每个列表中的一个元素组成。 我可以做到直到第二个列表的长度为 1。但是增加长度后,我没有得到预期的 output。
例如,代码是
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())
它返回预期的 output 这是[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]但每当我倾向于增加第二个列表的元素时,它会显示一个不正确的答案。 谁能建议我如何解决这个问题?
使用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())
output
[('vanilla', 'chocolate sauce'), ('vanilla', 'banana sauce'), ('chocolate', 'chocolate sauce'), ('chocolate', 'banana sauce')]
我认为这可以通过使用两个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
如果你想有多个选项的组合,那么代码会更复杂......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.