【发布时间】:2015-12-01 02:45:05
【问题描述】:
这行得通:
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 - for x in food - 那么 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'
这与使用元组或列表作为字典的键无关......或者是吗?!
【问题讨论】:
-
请将循环变量更改为
food以外的其他值,因为您将覆盖food的早期值 -
for food in food你考虑过用不同的名字来引用它的内容吗? -
food是列表还是字符串? Python 似乎认为它是一个列表,而您正在使用它来索引字典,这是一个禁忌。字典键必须是不可变的。 -
“把食物换成别的东西”是什么意思? “其他任何东西”的可能值是什么?你要更改
food的哪个实例? -
如果我将 food 更改为 foot_type 或任何其他变量名,我会得到 ' unhashable type: 'list' ;所以问题是为什么 For food in food 循环只工作而不是 For food_type in food ?还是食物中的 x ?
标签: python list loops dictionary tuples