[英]Appending From a Dictionary to a List
我目前正在开发一个用户可以订购披萨的程序。 我在从字典中获取特定值并将其放入列表中的最佳方法存在一些问题,我最终可以使用该列表为客户提供最终总数。
我的问题是:我将如何获取用户的输入,将其与“键”和 append 将“值”匹配到一个列表中,以便以后用于用户最终总计。
这是我目前拥有的字典:
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()
我知道上面的代码是不正确的,但是,我正在寻找任何能让我朝着正确方向前进的东西。
没有经过彻底测试,但这里有一种方法可以通过注释解释思考过程:(请注意,您可以使用更少的代码实现相同的目标,但是使用简单的对象和明确定义的属性编写代码可以更容易维护更大的应用程序因此是养成的好习惯)
# 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 循环放在 function 中,你可以这样做:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.