2016-08-25 183 views
-1

我真的被卡住了,我正在閱讀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'

+0

你回溯做,你貼的代碼實際上並不匹配。不是說'int()'調用很重要。 –

回答

1

你的字典中的值都是字符串:

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產生對齊的數字。

+0

謝謝,現在這麼簡單 –

0

您正在嘗試sum一串字符串,這是行不通的。你需要嘗試sum他們之前的字符串爲數字轉換:

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

另外,聲明你的價值觀爲整數用的不是字符串開始。

0

產生此錯誤是因爲您在嘗試總和('12','42',..),所以你需要每榆樹轉換爲int

item_total = sum(stuff.values()) 

通過

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

錯誤在於行

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)