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

所以我有这个代码:


 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 total

shopping_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))

我想知道我是否能够打印出每件商品的价格,正如你所看到的,我已经尝试过但没有成功。


慕婉清6462132
浏览 107回答 2
2回答

潇湘沐

这里不需要一个函数,没有它就可以轻松完成。stock ={&nbsp; &nbsp; "banana": 6,&nbsp; &nbsp; "apple": 0,&nbsp; &nbsp; "orange": 32,&nbsp; &nbsp; "pear": 15}prices = {&nbsp; &nbsp; "banana": 4,&nbsp; &nbsp; "apple": 2,&nbsp; &nbsp; "orange": 1.5,&nbsp; &nbsp; "pear": 3}shopping_cart = ["pear", "orange", "apple"]shopping_cart = [("pear",1), ("orange", 3), ("apple",10)]for i in shopping_cart:&nbsp; &nbsp; if stock[i[0]] - i[1] < 0:&nbsp; &nbsp; &nbsp; &nbsp; shopping_cart.pop(shopping_cart.index(i))&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; stock[i[0]] -= i[1]print("----------------")print("&nbsp; &nbsp; &nbsp;Bill")print("----------------")for i in shopping_cart:&nbsp; &nbsp; print(f"{i[0]} x{i[1]} @&nbsp; £{prices[i[0]]}")print("----------------")print(sum([prices[i[0]] * i[1]&nbsp; for i in shopping_cart]))print("----------------")解释:购物车由元组组成第一个元素 it 项目第二是金额第一个 for 循环检查是否有足够的库存来购买该商品,如果有,则从库存中删除该金额并继续进行如果没有,它会从购物车中删除该商品(是的,您可以修改它,当库存不足但库存> 0时,您可以向用户出售剩余库存。)第二个for循环使用 f 字符串格式化输出sum(列表理解)轻松获得商品价格*购买金额之和!

慕容708150

您可以使该函数compute_bill返回当前商品、价格,并检查该商品是否有库存。如果可以的话,减少数量。stock = {&nbsp; &nbsp; "banana": 6,&nbsp; &nbsp; "apple": 0,&nbsp; &nbsp; "orange": 32,&nbsp; &nbsp; "pear": 15}prices = {&nbsp; &nbsp; "banana": 4,&nbsp; &nbsp; "apple": 2,&nbsp; &nbsp; "orange": 1.5,&nbsp; &nbsp; "pear": 3}def compute_bill(shopping_list):&nbsp; &nbsp; for item in shopping_list:&nbsp; &nbsp; &nbsp; &nbsp; if stock.get(item, 0) > 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield item, prices.get(item, 0),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stock[item] -= 1shopping_list = ["pear", "orange", "apple"]&nbsp;print("Items Purchased")print("---------------")total = 0for item, value in compute_bill(shopping_list):&nbsp; &nbsp; print('{:<10} @{}'.format(item.title(), value))&nbsp; &nbsp; total += valueprint("---------------")print("Total: £{:.2f}".format(total))印刷:Items Purchased---------------Pear&nbsp; &nbsp; &nbsp; &nbsp;@3Orange&nbsp; &nbsp; &nbsp;@1.5---------------Total: £4.50
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python