python:如何使用字典和for循环来计算(项目,数量)元组列表的总成本?

发布于 2025-01-11 22:43:36 字数 468 浏览 0 评论 0原文

这是我第一次使用堆栈溢出,因为我刚刚开始学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静赏你的温柔 2025-01-18 22:43:36

迭代每个元素,解包元组:

total = 0
for bought_item in bought_items:
    item_name = bought_item[0]
    quantity = bought_item[1]
    total += stationery_prices[item_name] * quantity

print(total)

请注意,这比必要的更详细(例如,在 for 循环中没有元组解包)。我选择这样做是为了减少因不熟悉的语法而可能产生的混淆。如果你想在一行中完成它,你可以这样做:

total = sum(stationery_prices[item_name] * quantity 
    for item_name, quantity in bought_items)

Iterate over each element, unpacking the tuple:

total = 0
for bought_item in bought_items:
    item_name = bought_item[0]
    quantity = bought_item[1]
    total += stationery_prices[item_name] * quantity

print(total)

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:

total = sum(stationery_prices[item_name] * quantity 
    for item_name, quantity in bought_items)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文