无法修复Python错误AttributeError:';int';对象没有属性';获取';
我的源代码无法修复Python错误AttributeError:';int';对象没有属性';获取';,python,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:"
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'
你能告诉我如何修复这个错误吗?如果你能解释一下为什么这不起作用,我将不胜感激
提前谢谢你你为什么不写以下内容呢:
def显示_库存(库存):
打印(“Itme列表”)
项目总数=0
对于inventory.items()中的k、v:
打印(str(k)+str(v))
item_total=item_total+v#在字典中,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
应在字典上调用get
(即inventory
)
无需调用get
,因为循环中v=inventory[k]
如果k
不存在,则不需要设置默认值,因为inventory.items()中的k,v的仅在现有项之间循环
该错误与v.get(k,0)
一致。.get()
函数的语法为
.get(,
并在字典中输出一个值
而通常的[]
方法会在密钥不存在时抛出错误
在inventory.items()中迭代k,v的键值对时,特定于您的代码:
,该键保证存在
由于您已经在迭代字典中的值,因此您可以简单地使用
项目总数+=v
关于print(str(k)+str(v))
的其他反馈,您可以尝试以下方法:
+
符号打印(str(k)+''+str(v))
只允许字符串
,
表示法打印(k,v)
,它允许混合使用字符串
和列表
打印中使用,
符号(“项目总数:”,项目总数)
rope 1
torch 6
coin 42
Shuriken 1
arrow 12
The total number of items: 62
顺便说一下,打印(“Itme列表”)
中有一个打字错误
干杯!int没有get属性是有道理的。您认为get在这里应该做什么呢?
对于dict.items()中的k,v
。因此v
接受以k
为键的元素的值。显然,此元素是一个int,因此您不能将get方法应用于整数。get可以应用于dict,例如库存。因此,两个正确的行是item\u total+v
或item\u total+inventory。get(k)
Welcome@Eric。我不明白为什么这个问题是-2,还需要一个人来帮助中和反对票