无法修复Python错误AttributeError:“int”对象没有属性“get”

2024-04-25 14:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的源代码

def display_inventory(inventory):
    print("Itme list")
    item_total = 0
    for k,v in inventory.items():
        print(str(k) + str(v))
        item_total = item_total + v.get(k,0)
    print("The total number of items:" + str(item_total))

stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)

错误消息

AttributeError: 'int' object has no attribute 'get'

你能告诉我如何修复这个错误吗?如果你能解释一下为什么这不起作用,我将不胜感激

先谢谢你


Tags: forget源代码def错误displayitemsitem
3条回答

你为什么不简单地写下以下内容:

def display_inventory(inventory):
    print("Itme list")
    item_total = 0
    for k,v in inventory.items():
        print(str(k) + str(v))
        item_total = item_total + v  # <<< CHANGE HERE
    print("The total number of items:" + str(item_total))

stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)

因为在这种情况下,值v是与要相加的产品对应的数字。不需要使用get()进一步查找字典,因为您已经拥有了所需的值

  1. ^应在字典上调用{}(即inventory
  2. 不需要调用get,因为v = inventory[k]在循环中
  3. 如果k不存在,则不需要使用默认值,因为for k,v in inventory.items()仅循环现有项

在您的字典中,v是一个整数。字典中的所有内容都是在inventory.items()中获取的。您正试图从整数中获取某些内容。因此,它显示了一个错误。解决方案是简单地更改为v

def display_inventory(inventory: dict):
    print("Item list")
    item_total = 0
    for k,v in inventory.items():
        print(str(k) + str(v))
        item_total = item_total + v #=== Here
    print("The total number of items:" + str(item_total))

stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)

以及输出:

rope1
torch6
coin42
Shuriken1
arrow12
The total number of items:62

相关问题 更多 >