Python 3.4 Python:类型错误不支持+;的操作数类型:';int';和';str';

Python 3.4 Python:类型错误不支持+;的操作数类型:';int';和';str';,python-3.4,Python 3.4,我真的被卡住了,我目前正在阅读Python——如何自动化那些无聊的东西,我正在做一个实践项目 为什么它会标记错误?我知道这和项目总数有关 import sys stuff = {'Arrows':'12', 'Gold Coins':'42', 'Rope':'1', 'Torches':'6', 'Dagger':'1', } def displayInventory(inventory): print("Inventory:") i

我真的被卡住了,我目前正在阅读Python——如何自动化那些无聊的东西,我正在做一个实践项目

为什么它会标记错误?我知道这和项目总数有关

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行,在 显示库存(物品) displayInventory中第11行的文件“C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py” item_total=int(总和(stuff.values()) TypeError:不支持+:“int”和“str”的操作数类型


您的字典值都是字符串:

stuff = {'Arrows':'12',
     'Gold Coins':'42',
     'Rope':'1',
     'Torches':'6',
     'Dagger':'1', }
但您尝试对这些字符串求和:

item_total = sum(stuff.values())
sum()

>>> 0 + '12'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
您并不需要将这些值设置为字符串,因此更好的解决方案是将这些值设置为整数:

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

要生成与对齐的数字,

您正在尝试对一组字符串进行求和,这是行不通的。在尝试对字符串进行求和之前,需要将字符串转换为数字:

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

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

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

item_total = sum(stuff.values())

这个错误是一致的

a = sum(stuff.values()) 

字典中的值类型是
str
,而不是
int
,请记住
+
是字符串之间的串联和整数之间的加法运算符。找到下面的代码,应该解决这个错误,将它从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)

您的回溯和您发布的代码实际上不匹配。这里的
int()
调用并不重要。谢谢,现在很简单
a = sum(stuff.values()) 
item_total = sum(stuff.values())
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)