我需要一个函数来比较两个列表并从第一个列表中提取值。 我有一份清单。
menu_list = [['1', 'burrito', '6.99'], ['2', 'stir fry', '7.99'], ['3', 'hamburger', '8.99'], ['4', 'cheeseburger', '9.99'], ['5', 'french fries', '4.99']]
我有最终名单
cart = ['burrito', 'stir fry', 'burrito']
我需要知道如何从第一个列表中提取第二个列表中项目的值并将它们加在一起。 (6.99 + 7.99 + 6.99 = 21.97)
def subtotal(menu_list, cart):
total = 0
for i in range(len(menu_list)):
if menu_list[i][0] == i:
item_name = menu_list[i][1]
for j in cart:
if j == item_name:
total += int(menu_list[i][2])
print('Your subtotal is ', total)
return total
对我来说绝对一无所获
您的代码存在很多问题,因此我建议采用不同的方法:对于您的菜单,使用字典而不是列表。字典允许您通过键(商品名称)查找值(在本例中为价格),而无需遍历整个字典来查找它。您可以将
menu_list
转换为字典一次,然后继续使用:
menu_dict = {item[1]: float(item[2]) for item in menu_list}
此循环遍历
item
中的每个 menu_list
。每个 item
本身都是一个包含三个字符串的列表:索引、商品名称和商品价格。字典理解创建一个字典,其键是 item
的第二个元素(即其名称 item[1]
),其值是 item
的第三个元素(即其价格,转换为 float
: float(item[2])
)。根据您的 menu_list
,这会产生以下字典:
{
'burrito': 6.99,
'stir fry': 7.99,
'hamburger': 8.99,
'cheeseburger': 9.99,
'french fries': 4.99
}
接下来,让我们改进您的
subtotal
功能:
def subtotal(menu, cart):
total = 0
for item_name in cart:
try:
total += menu[item_name]
except KeyError:
print(f"Sorry, we don't sell {item_name}")
return total
在这里,
subtotal
需要菜单字典和购物车列表。
此函数循环遍历 item_name
列表中的每个 cart
,并尝试在 menu
字典中查找其值。如果在字典中找到 item_name
,则价格将添加到 total
。如果没有,Python 会引发 KeyError
。然后,这个 KeyError
被 except KeyError
子句捕获,并打印一条不错的消息,并且不会将该项目添加到 total
中。
cart = ['burrito', 'stir fry', 'burrito', 'tiramisu']
cart_subtotal = subtotal(menu_dict, cart)
现在,
cart_subtotal
是预期值,21.97
,并打印一条消息,表明菜单上没有提拉米苏。
在这种情况下,使用字典而不是数组更方便。这样可以使用每个商品的键来更快地执行搜索以获得其价格。
menu_list = {
"burrito": 6.99,
"stir fry": 7.99,
"hamburger": 8.99
}
cart = ['burrito', 'stir fry', 'burrito']
total = 0
for elements in cart:
total += menu_list[elements]
print(total)
# 21.97
#
# Process finished with exit code 0