Python:类型错误不支持的操作数类型为+:'int'和'str'
我真的被卡住了,我正在阅读Python - 如何自动化无聊的东西,我正在做一个实践项目。Python:类型错误不支持的操作数类型为+:'int'和'str'
为什么会标记错误?我知道这与item_total有关。
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
def displayInventory(inventory):
print("Inventory:")
item_total = sum(stuff.values())
for k, v in inventory.items():
print(v + ' ' + k)
a = sum(stuff.values())
print("Total number of items: " + item_total)
displayInventory(stuff)
错误,我得到:
Traceback (most recent call last): File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 17, in displayInventory(stuff) File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 11, in displayInventory item_total = int(sum(stuff.values())) TypeError: unsupported operand type(s) for +: 'int' and 'str'
你的字典中的值都是字符串:
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
但你尝试总结这些字符串:
item_total = sum(stuff.values())
sum()
使用初始值,一个整数的0
,所以它试图用0 + '12'
,这不是在Python有效的操作:
>>> 0 + '12'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
你必须所有的值转换为整数;无论是总结的时候开始,或者:
item_total = sum(map(int, stuff.values()))
你并不真的需要这些值是字符串,所以更好的解决方案是使值的整数:
stuff = {
'Arrows': 12,
'Gold Coins': 42,
'Rope': 1,
'Torches': 6,
'Dagger': 1,
}
,然后调整你的库存循环转换那些字符串打印时:
for k, v in inventory.items():
print(v + ' ' + str(k))
或者更好的是:
for item, value in inventory.items():
print('{:12s} {:2d}'.format(item, value))
与string formatting产生对齐的数字。
谢谢,现在这么简单 –
您正在尝试sum
一串字符串,这是行不通的。你需要尝试sum
他们之前的字符串为数字转换:
item_total = sum(map(int, stuff.values()))
另外,声明你的价值观为整数用的不是字符串开始。
产生此错误是因为您在尝试总和('12','42',..),所以你需要每榆树转换为int
item_total = sum(stuff.values())
通过
item_total = sum([int(k) for k in stuff.values()])
错误在于行
a = sum(stuff.values())
和
item_total = sum(stuff.values())
值类型你的字典是str
和不是int
,请记住+
是字符串和整数之间的加法运算符之间的串联。找到下面的代码,就可以解决这个错误,将其转换成int数组从STR阵列由映射
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1'}
def displayInventory(inventory):
print("Inventory:")
item_total = (stuff.values())
item_total = sum(map(int, item_total))
for k, v in inventory.items():
print(v + ' ' + k)
print("Total number of items: " + str(item_total))
displayInventory(stuff)
你回溯做,你贴的代码实际上并不匹配。不是说'int()'调用很重要。 –