簡體   English   中英

計算字典有序列表的總和

[英]Calculating sum of ordered list of dictionaries

我試圖找出如何返回字典順序列表中給出的幾個值的總和

menu = {
    1: {"name": 'espresso',
        "price": 1.99},
    2: {"name": 'coffee', 
        "price": 2.50},
    3: {"name": 'cake', 
        "price": 2.79},
    4: {"name": 'soup', 
        "price": 4.50},
    5: {"name": 'sandwich',
        "price": 4.99}
}


def calculate_subtotal(order):
  
return subtotal

def take_order():
    display_menu()
    order = []
    count = 1
    for i in range(3):
        item = input('Select menu item number ' + str(count) + ' (from 1 to 5): ')
        count += 1
        order.append(menu[int(item)])
    return order
  • def calculate_subtotal(order) 應該接受一個參數,即訂單列表並返回總和
    訂單列表中商品的價格。
  • 我是否必須使用 for 循環來遍歷值並對每個值求和?
  • 如何訪問列表中的字典?

假設一個人訂購了以下內容:

orders = [
    {"name": "espresso", "price": 1.99},
    {"name": "espresso", "price": 1.99},
    {"name": "soup", "price": 4.99},
]

你現在有一個dict list list進行索引會返回對字典的引用。 例如:

first_order = orders[0]
print(first_order)

將打印:

{'name': 'espresso', 'price': 1.99}

使用這些知識,您可以像這樣遍歷訂單:

total = 0.0
for order in orders:
    total += order["price"]

每個order都將是您在上面看到的dict

如果您對它們感到滿意,您也可以使用理解。

total = sum(order["price"] for order in orders)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM