我对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']]
有人能给我个提示怎么修理吗?在
看来您需要返回值。在
尝试:
对于这个问题,我甚至有一个较短版本的代码。我使用列表理解来解决这个问题:
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']]
;您只需使用
for i in elements
并从两个列表中获取每个元素并附加到新列表中。(本例中为k)。在