Python:为+:'int'和'str'输入错误不支持的操作数类型

时间:2016-08-25 09:55:43

标签: python-3.4

我真的被困了,我正在阅读Python - 如何自动化无聊的东西,我正在做一个练习项目。

为什么会出现错误?我知道这与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)

我得到的错误:

  

追踪(最近一次通话):     文件“C:/ Users / Lewis / Dropbox / Python / Function displayInventory p120 v2.py”,第17行,in       displayInventory(东东)     在displayInventory中输入文件“C:/ Users / Lewis / Dropbox / Python / Function displayInventory p120 v2.py”,第11行       item_total = int(sum(stuff.values()))   TypeError:+:'int'和'str'

的不支持的操作数类型

4 个答案:

答案 0 :(得分:1)

您的字典值都是字符串:

c

但是你试着总结这些字符串:

stuff = {'Arrows':'12',
     'Gold Coins':'42',
     'Rope':'1',
     'Torches':'6',
     'Dagger':'1', }

item_total = sum(stuff.values()) 使用sum()的起始值,整数,因此它尝试使用0,这不是Python中的有效操作:

0 + '12'

您必须将所有值转换为整数;要么开始,要么总结:

>>> 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))

使用string formatting生成对齐的数字。

答案 1 :(得分:0)

你正在尝试sum一串字符串,这些字符串不起作用。您需要在尝试sum之前将字符串转换为数字

item_total = sum(map(int, stuff.values()))

或者,将值声明为整数而不是字符串。

答案 2 :(得分:0)

产生此错误是因为您尝试求和('12','42',..),因此您需要将每个elm转换为int

item_total = sum(stuff.values())

通过

item_total = sum([int(k) for k in stuff.values()])

答案 3 :(得分:0)

错误在于行

item_total = sum(stuff.values())

str

字典中的值类型为int而不是+,请记住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) 是字符串与整数之间的加法运算符之间的连接。找到下面的代码,应该解决错误,将其从str数组转换为int数组是通过映射完成的

{{1}}