【问题标题】:loop tuple list - TypeError: unhashable type: 'list'循环元组列表-TypeError:不可散列的类型:'list'
【发布时间】: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


【解决方案1】:

假设 food 是一个列表,你只需要将 for 循环更改为:

for food_type in food:
    total += prices[food_type]

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2019-01-29
    • 2013-10-22
    • 2013-01-23
    • 2017-06-21
    • 1970-01-01
    • 2018-10-05
    • 2012-01-21
    • 2021-12-17
    相关资源
    最近更新 更多