用Python(TestDome)打印字符串

2024-10-02 04:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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']]

有人能给我个提示怎么修理吗?在


Tags: inselfforlendefrangemachineprint
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()) 

对于这个问题,我甚至有一个较短版本的代码。我使用列表理解来解决这个问题:

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']]

和13;
和13;

您只需使用 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']]

相关问题 更多 >

    热门问题