【问题标题】:Python: Unhashable error, listsPython:不可散列的错误,列表
【发布时间】:2017-03-07 23:05:12
【问题描述】:

这个不同...我的代码围绕用户输入的信息工作,并使用该信息执行各种操作,例如存储信息、进行乘法和添加,以及将其存储为变量。在代码的末尾,我希望从用户输入的内容中打印出收据,并在字典中翻译成它的其他名称。呼,这是我的代码:

print("Hi There! Welcome to sSpecialists!")
print("To start shopping, note down what you want to buy and how much of it")
print("Here are the purchasable items")
print("~~~~~")
print("12345670 is a hammer (£4.50)")
print("87654325 is a screw driver (£4.20)")
print("96385272 is a pack of 5 iron screws (£1.20)")
print("74185290 is pack of 20 100mm bolts (£1.99)")
print("85296374 is a pack of 6 walkers crisps (£1)")
print("85274198 is haribo pack (£1)")
print("78945616 is milk (£0.88)")
print("13246570 is a bottle of evian water (£0.99)")
print("31264570 is kitkat original (£0.50)")
print("91537843 is a cadbury bar (£1)")
print("~~~~~")
items = {12345670 : 'hammer',
         87654325 : 'screwDriver',
         96385272 : 'packOf5IronnScrews',
         74185290 : 'packOf200mmBolts',
         85296374 : 'packOf6WalkersCrisps',
         85274198 : 'hariboPack',
         78945616 : 'milk',
         13246570 : 'bottleOfEvianWater',
         31264570 : 'kitkatOriginal',
         91537843 : 'cadburyBar'}
print("Alright, now start typing what you want to order")
print(" ")
subtotal = 0
full_list = " "
chos_items = []
while full_list != "":
    print(" ")
    full_list = input("Type: ")
    if full_list == 'end':
        break
    amount = int(input("Amount: "))
    item = int(full_list)
    if item in items:
        print("That would be {} {}(s)".format(amount, items[item]))
        if full_list == '12345670':
            price = (4.50 * amount)
            print("Added Hammer(s)")
            print("Added "+str(price))
            subtotal = subtotal + price
            if full_list == '87654325':
            price = (4.20 * amount)
            subtotal = subtotal + price
            print("Added Screw Driver(s)")
            print("Added "+str(price))
        if full_list == '96385272':
            price = (1.20 * amount)
            subtotal = subtotal + price
            print("Added Pack of 5 iron 
            print("Added "+str(price))
        if full_list == '74185290':
            price = (1.99 * amount)
            subtotal = subtotal + price
            print("Added Pack of 20 100mm bolts")
            print("Added "+str(price))
        if full_list == '85296374':
            price = (1.00 * amount)
            subtotal = subtotal + price
            print("Added Pack of 6 Walkers crisps")
            print("Added "+str(price))
        if full_list == '85274198':
            price = (1.00 * amount)
            subtotal = subtotal + price
            print("Added Haribo pack(s)")
            print("Added "+str(price))
        if full_list == '78945616':
            price = (0.88 * amount)
            subtotal = subtotal + price
            print("Added bottle(s) of milk")
            print("Added "+str(price))
        if full_list == '13246570':
            price = (0.99 * amount)
            subtotal = subtotal + price
            print("Added bottle(s) Evian water")
            print("Added "+str(price))
        if full_list == '31264570':
            price = (0.50 * amount)
            subtotal = subtotal + price
            print("Added bar(s) of Kitkat original")
            print("Added "+str(price))
        if full_list == '91537843':
            price = (0.50 * amount)
            print("Added Cadbury bar(s)")
            print("Added "+str(price))
        if full_list != "":
            chos_items.append(full_list)
total = round(subtotal)
print("Your subtotal is " +str(total))
print(" ")
print("That would be, []".format(items[full_list]))
print(" ")
print("Your recipt is")
print(" ")

我的代码是一堆类似的东西,但疯狂背后有方法。我相信问题发生在print("That would be, []".format(items[chos_items]))。当我运行它时,这就是输出的内容

    print("That would be, []".format(items[chos_items]))
TypeError: unhashable type: 'list'

我尝试将列表更改为麻烦,但这没有帮助。我一生不知道如何解决它。请帮忙,谢谢>_

【问题讨论】:

  • 只是健全性检查,但不是您正在寻找花括号而不是方括号的语法吗? {} 不是 []?
  • 应该是 print("那就是,{}".format(items[chos_items]))
  • print("That would be, {}".format(items[chos_items])) 我还没有查看您的代码,但您需要阅读 if/elif/else 而不仅仅是 if(必须测试 every条件)
  • 这是第二稿,但我试过了
  • 您正在尝试使用列表索引字典 - 列表不是有效的 dict 键,因为它们不可散列。您的字符串格式还有其他问题

标签: python list typeerror


【解决方案1】:

两大问题:

1) 您将结果存储在chos_items 中,然后不对它们做任何事情。 full_items,当你退出while循环时,包含"end"""

print("That would be, {}".format(' '.join([items[int(item)] for item in chos_items])))

会给你一个所有选择的项目的列表,但它不会给出多少,因为你不存储那个值。

2) 您没有充分利用 python dicts:

if item in items:

您检查项目是否在项目中作为字典,但随后不利用字典。

items = {'12345670' : {'name' : 'Hammer', 'price' : 4.50},
         '87654325' : {'name' : 'screwDriver', 'price' : 4.20}}

如果这是您的字典,那么您可以执行以下操作:

for item in items:
    print("{} is a {} (£{:0.2f})".format(item, items[item]['name'], items[item]['price']))

它将为您打印出物品清单及其价格:

87654325 is a screwDriver (£4.20)
12345670 is a Hammer (£4.50)

item 是数字,item['name'] 是名称,item['price'] 是价格。然后,您可以将您的 if/if/if/if 块合并到一个查找中:if item in items:

这将大大简化您的逻辑,因为 dict 完成了大部分工作。

【讨论】:

  • @FlagShipKILLER 我鼓励您再试一次,并查找有关如何使用字典的教程。他们非常强大。这故意是一个不完整的解决方案,因此您必须完成工作才能使其正常工作。
  • 我明白,谢谢,但认真的。一个最后的问题,我怎样才能得到一个只有小数点后 2 位的输出
  • {:0.2f} 告诉格式化程序 .2 在小数点后有 2 位数字,并且它应该期望 f 浮点数。
【解决方案2】:

您收到此错误是因为您将 list 对象作为键传递给您的 items 字典。下面是一个例子来说明这一点:

>>> my_dict = {'a': 123, 'b': 234}
>>> my_dict[[]]  # accessing `my_dict` with `[]` as value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

另外,您需要使用{}string.format() 而不是[],否则您的内容将不会添加到字符串中。例如:

>>> 'Hello World []'.format('StackOverflow')
'Hello World []'
>>> 'Hello World {}'.format('StackOverflow')
'Hello World StackOverflow'

【讨论】:

  • 如何解决?进一步解释对不起,我只是在高中
  • 它有效,但是它只显示最近输入的数字
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 2019-05-10
  • 2022-01-11
相关资源
最近更新 更多