[英]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
假設一個人訂購了以下內容:
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.