我是Python
的新手,因此决定在TestDome
做些运动。以下是该网站上easy question的代码,但是由于它没有按原样打印结果,因此我得到零分。
class IceCreamMachine:
all={}
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
for i in range(0,len(self.ingredients)):
for j in range(0,len(self.toppings)):
print ([self.ingredients[i],self.toppings[j]])
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]
有人可以提示如何修复它吗?
答案 0 :(得分:3)
看起来您需要返回值。
尝试:
class IceCreamMachine:
all={}
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
res = []
for i in self.ingredients:
for j in self.toppings:
res.append([i, j])
return res
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops())
答案 1 :(得分:1)
针对此问题,我什至有一个较短的代码版本。我正在使用列表理解来解决此问题:
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
return [[i,j] for i in self.ingredients for j in self.toppings]
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]
答案 2 :(得分:0)
您无需使用for i in range(0,len(self.ingredients)):
之类的范围,而只需使用
for i in elements
并从两个列表中获取每个元素并追加到新列表中。 (在这种情况下为k)。
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
k=[]
for i in self.ingredients:
for j in self.toppings:
k.append([i,j])
return k
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]