亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何打印購物清單中某件商品的單獨價格

如何打印購物清單中某件商品的單獨價格

慕婉清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 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號