从字典追加到列表

2024-09-28 19:24:40 发布

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

我目前正在开发一个用户可以订购比萨饼的程序。我对从字典中获取特定值并将其放入列表的最佳方法存在一些问题,我最终可以使用该列表向客户提供最终的总数

我的问题是:如何获取用户的输入,将其与“键”匹配,并将“值”附加到一个列表中,以便以后用于用户的最终合计。

这是我目前拥有的字典:

sizePrice = {
    'small': 9.69, 
    'large': 12.29, 
    'extra large': 13.79, 
    'party size': 26.49
}

我写过一个例子:

class PizzaSize():
    """" Takes the customers size requested and returns total cost of that pizza size"""

    sizePrice = {
        'small': 9.69, 
        'large': 12.29, 
        'extra large': 13.79, 
        'party size': 26.49
        }

    ordered_size= []

    def size(self):
        self.size_wanted = input("What size pizza would you like? ")
        self.size_wanted = self.size_wanted.title()
        customer_size = self.size_price[self.size_wanted]
        odered_size.append(customer_size)

order = PizzaSize()

order.size()

我知道上面的代码是不正确的,但是,我正在寻找任何能让我走上正确方向的东西


Tags: 用户self列表size字典partyordercustomer
1条回答
网友
1楼 · 发布于 2024-09-28 19:24:40

虽然没有经过彻底的测试,但这里有一种方法可以通过解释思考过程的注释来实现:(注意,您可以用更少的代码实现同样的效果,但是使用简单的对象和明确定义的属性编写代码可以更容易地维护更大的应用程序,因此是一个好习惯)

# We'll ask the user for a number since those are easier to input,
# especially in console applications without auto-complete/other visual feedback.
# Ideally I would suggest looking into Enums,
# but I'm guessing you're just starting out so this should suffice

size_mappings = {
    1: "small",
    2: "large",
    3: "extra large"
}

# Note that we could have mapped numbers to prices as well,
# but it's not very readable. Readability is supreme. Enums solve this problem.

cost_mappings = {
    "small": 6,
    "large": 10,
    "extra large": 12
}

# I like my objects simple, and designing classes etc. comes with practice
# but intuitively I would want Pizza as one object with a single size property
# Cost could also have been a property but this application is simple enough
# and I didn't see a need to make a part of the object,
# especially since we already have a mapping declared above.

# In general you want objects to have properties and methods to access
# those properties. A pizza can have a size,
# and the way you get the pizza's size is by calling get_size()


class Pizza():
    def __init__(self, size):
        self.size = size

    def set_size(self, size):
        self.size = size

    def get_size(self):
        return self.size()

    def get_cost(self):
        return cost_mappings[self.size]

# Once again, intuitively an order can have multiple pizzas, so we
# construct an order object with a list of pizzas.
# It's an object with a property to add pizzas to it,
# as well as compute the order total (which is what you wanted to do).
# To compute the total, we go through all the pizzas in the order,
# access their cost and return the total.


class Order():
    def __init__(self):
        self.pizzas = []

    def addPizza(self, pizza):
        self.pizzas.append(pizza)

    def getTotal(self):
        total = 0
        for pizza in self.pizzas:
            total += pizza.get_cost()
        return total

# start processing the order
order = Order()

# This is an infinite loop, implying the user can continue adding pizzas
# until they are satisfied, or dead from heart disease (*wink*)

while True:
    try:
        # Need a way to exit the loop, here it is by pressing q and then enter
        response = input("What size pizza would you like?\n\
(1: small | 2: large | 3: extra large)\n \
Press q to finish order and compute the total\n"
                         )
        # This is where we check if the user is done ordering
        if response == 'q':
            break
        # The input is taken in as a string, 
        # convert it to an integer for processing
        # since our dictionary has integers as keys
        size_wanted = int(response)
        # A few things going on here.
        # Lookup the string version of the size we stored in the dictionary
        # Construct a pizza with a specific size, "small", "large" etc.
        # The pizza object gets stored inside the order object 
        # through the addPizza method
        size_wanted = size_mappings[size_wanted]
        order.addPizza(Pizza(size_wanted))
    except:
        print("An error occurred, please try again")

# The beauty of OOP, the logic to compute the total is already there.
# Call it and be done. 
print("Your total is: ", "$" + str(order.getTotal()))

让我知道如果你想进一步澄清,很乐意帮助

根据要求进行澄清(查看注释以了解解释):

如果要将while循环放入函数中,可以执行以下操作:

def run():
    while True:
    # code here

# Single function call in the entire file
# But you must have atleast one to make sure
# SOMETHING happens. Every other function can 
# be called inside run(), the "main" function
run()

相关问题 更多 >