【问题标题】:Print Strings in Python (TestDome)在 Python 中打印字符串 (TestDome)
【发布时间】:2018-08-07 07:10:30
【问题描述】:

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

任何人都可以提示如何解决它吗?

【问题讨论】:

    标签: python collections


    【解决方案1】:

    看起来你需要返回值。

    试试:

    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()) 
    

    【讨论】:

      【解决方案2】:

      对于这个问题,我什至有更短的代码版本。我正在使用列表推导来解决这个问题:

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

      【讨论】:

        【解决方案3】:

        而不是像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']]
        

        【讨论】:

          猜你喜欢
          • 2013-10-10
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 2011-10-17
          • 1970-01-01
          • 2012-12-12
          • 2018-06-13
          • 2016-01-20
          相关资源
          最近更新 更多