python:如何使用字典和for循环来计算(项目,数量)元组列表的总成本?
这是我第一次使用堆栈溢出,因为我刚刚开始学习 python,所以如果我没有像我应该的那样清楚地表达事情,我深表歉意!
我正在解决一个问题,要求我开一家文具店。有一本包含价格的字典:
stationery_prices = {
'pen': 0.55,
'pencil': 1.55,
'rubber': 2.55,
'ruler': 3.55
}
我必须要求用户输入他们想要的商品和数量,然后将其排列在元组列表中。
现在我有一个如下所示的列表:
[('pen', 1), ('pencil', 2)]
如何使用 for 循环来引用原始价格字典并添加用户的总成本?
非常感谢
this is my first time using stack overflow as I am just starting to learn python so apologies if I don't phrase things as clearly as I should!
I am working on a problem which asks me to set up a stationery shop. There is a dictionary with prices:
stationery_prices = {
'pen': 0.55,
'pencil': 1.55,
'rubber': 2.55,
'ruler': 3.55
}
I have to ask the user to input what item they would like and what quantity, and then arrange this in a list of tuples.
So now I have a list that looks like this:
[('pen', 1), ('pencil', 2)]
How do I use a for loop to refer back to the original dictionary of prices and add up the total cost for the user?
Thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
迭代每个元素,解包元组:
请注意,这比必要的更详细(例如,在
for
循环中没有元组解包)。我选择这样做是为了减少因不熟悉的语法而可能产生的混淆。如果你想在一行中完成它,你可以这样做:Iterate over each element, unpacking the tuple:
Note that this is more verbose than necessary (e.g. no tuple unpacking in the
for
loop). I chose to do this to reduce possible confusion with unfamiliar syntax. If you wanted to do it in one line, you could do: