【问题标题】:How can I print items from a list? [duplicate]如何打印列表中的项目? [复制]
【发布时间】:2017-04-16 19:23:11
【问题描述】:

我正在尝试创建一个使用类和方法来制作餐厅的程序。通过创建一家餐厅,我的意思是它说明了他们的名字,他们提供的食物类型以及他们的营业时间。

我已经成功地做到了,但现在我正在尝试创建一个冰淇淋架,它继承自其父类 (Restaurant) 并创建一个子类 (IceCreamStand)。我的问题是,当我将冰淇淋口味列表存储在一个属性 (flavor_options) 中并打印它时,它会打印带有括号的列表。

我只想以常规句子格式打印列表中的项目。非常感谢任何帮助,谢谢!

    #!/usr/bin/python

    class Restaurant(object):
        def __init__(self, restaurant_name, cuisine_type, rest_time):
            self.restaurant_name = restaurant_name
            self.cuisine_type = cuisine_type
            self.rest_time = rest_time
            self.number_served = 0

    def describe_restaurant(self):
        long_name = "The restaurant," + self.restaurant_name + ", " + "serves " + self.cuisine_type + " food"+ ". It opens at "  + str(self.rest_time) + "am."
        return long_name

    def read_served(self):
        print("There has been " + str(self.number_served) + " customers served here.") 

    def update_served(self, ppls):
        self.number_served = ppls

        if ppls >= self.number_served:
            self.number_served = ppls # if the value of number_served either stays the same or increases, then set that value to ppls.
        else:
            print("You cannot change the record of the amount of people served.")
            # if someone tries decreasing the amount of people that have been at the restaurant, then reject themm.

    def increment_served(self, customers):
        self.number_served += customers

class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name, cuisine_type, rest_time):

        super(IceCreamStand, self).__init__(restaurant_name, cuisine_type, rest_time)
        self.flavors = Flavors()

class Flavors():
    def __init__(self, flavor_options = ["coconut", "strawberry", "chocolate", "vanilla", "mint chip"]):
        self.flavor_options = flavor_options

    def list_of_flavors(self):
        print("The icecream flavors are: " + str(self.flavor_options))

icecreamstand = IceCreamStand(' Wutang CREAM', 'ice cream', 11)
print(icecreamstand.describe_restaurant())
icecreamstand.flavors.list_of_flavors()

restaurant = Restaurant(' Dingos', 'Australian', 10)
print(restaurant.describe_restaurant())

restaurant.update_served(200)
restaurant.read_served()

restaurant.increment_served(1)
restaurant.read_served()

【问题讨论】:

  • " ".join(flavor_options)
  • 使用" ".join(self.flavor_options) 而不是str(...)
  • 非常感谢!现在可以使用了

标签: python python-2.7


【解决方案1】:

您可能希望使用.join() 将列表组合成一个字符串。

I.E.

flavor_options = ['Chocolate','Vanilla','Strawberry']

", ".join(flavor_options)

这将输出:

"Chocolate, Vanilla, Strawberry"

【讨论】:

  • 非常感谢,它成功了
猜你喜欢
  • 1970-01-01
  • 2017-10-28
  • 2022-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
相关资源
最近更新 更多