这有效:
shopping_list = ["banana", "orange", "apple"]
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
# food = tuple(food)
for food in food:
total += prices[food]
return total
print compute_bill(shopping_list)
但是如果我把食物转换成循环中的任何其他东西,例如X - 食物中的x - 那么python会给我以下错误(它只适用于食物中的食物。)
Traceback (most recent call last):
File "compute-shopping.py", line 25, in <module>
print compute_bill(shopping_list)
File "compute-shopping.py", line 21, in compute_bill
total += prices[food]
TypeError: unhashable type: 'list'
这与使用元组或列表作为字典的关键字无关......或者是它?!
答案 0 :(得分:2)
假设食物是一个列表,您只需要将for循环更改为:
for food_type in food:
total += prices[food_type]