为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印购物清单中某件商品的单独价格

如何打印购物清单中某件商品的单独价格

慕婉清6462132 2023-12-26 15:35:50
所以我有这个代码: stock = {    "banana": 6,    "apple": 0,    "orange": 32,    "pear": 15}prices = {    "banana": 4,    "apple": 2,    "orange": 1.5,    "pear": 3}def compute_bill(food):    total = 0    for item in food:        item = shopping_list(prices[key])        total += item    return totalshopping_list = ["pear", "orange", "apple"] total = sum([ prices[s] for s in shopping_list ])print("Items Purchased")print("---------------")for items in shopping_list:    print(items.title() + " @" + )print("---------------")print("Total: £{:.2f}".format(total))我想知道我是否能够打印出每件商品的价格,正如你所看到的,我已经尝试过但没有成功。
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

这里不需要一个函数,没有它就可以轻松完成。


stock ={

    "banana": 6,

    "apple": 0,

    "orange": 32,

    "pear": 15

}


prices = {

    "banana": 4,

    "apple": 2,

    "orange": 1.5,

    "pear": 3

}


shopping_cart = ["pear", "orange", "apple"]


shopping_cart = [("pear",1), ("orange", 3), ("apple",10)]


for i in shopping_cart:

    if stock[i[0]] - i[1] < 0:

        shopping_cart.pop(shopping_cart.index(i))

    else:

        stock[i[0]] -= i[1]


print("----------------")

print("     Bill")

print("----------------")

for i in shopping_cart:

    print(f"{i[0]} x{i[1]} @  £{prices[i[0]]}")

print("----------------")

print(sum([prices[i[0]] * i[1]  for i in shopping_cart]))

print("----------------")

解释:

购物车

  • 由元组组成

  • 第一个元素 it 项目

  • 第二是金额

第一个 for 循环

  • 检查是否有足够的库存来购买该商品,如果有,则从库存中删除该金额并继续进行

  • 如果没有,它会从购物车中删除该商品(是的,您可以修改它,当库存不足但库存> 0时,您可以向用户出售剩余库存。)

第二个for循环

  • 使用 f 字符串格式化输出

sum(列表理解)

  • 轻松获得商品价格*购买金额之和!


查看完整回答
反对 回复 2023-12-26
?
慕容708150

TA贡献1831条经验 获得超4个赞

您可以使该函数compute_bill返回当前商品、价格,并检查该商品是否有库存。如果可以的话,减少数量。


stock = {

    "banana": 6,

    "apple": 0,

    "orange": 32,

    "pear": 15

}


prices = {

    "banana": 4,

    "apple": 2,

    "orange": 1.5,

    "pear": 3

}



def compute_bill(shopping_list):

    for item in shopping_list:

        if stock.get(item, 0) > 0:

            yield item, prices.get(item, 0), 

            stock[item] -= 1



shopping_list = ["pear", "orange", "apple"] 


print("Items Purchased")

print("---------------")


total = 0

for item, value in compute_bill(shopping_list):

    print('{:<10} @{}'.format(item.title(), value))

    total += value


print("---------------")

print("Total: £{:.2f}".format(total))

印刷:


Items Purchased

---------------

Pear       @3

Orange     @1.5

---------------

Total: £4.50


查看完整回答
反对 回复 2023-12-26
  • 2 回答
  • 0 关注
  • 43 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信