0
这个工程:循环元组列表 - 类型错误:unhashable类型:“名单”
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 - 然后蟒蛇给我下面的错误(只用适用于食品中的食品。)
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'
这是不相关的使用元组或列表的密钥字典...或者是什么呢?!
请循环变量更改为'food'其他的东西,你要覆盖较早的值'food' –
“用于食物的食物”你有没有考虑用不同的名字来提及它的内容? – TigerhawkT3
“食物”是一个列表还是一个字符串? Python似乎认为它是一个列表,并且您正在使用它来索引一本字典,这是一个禁忌。字典键必须是不可变的。 –