2017-05-05 29 views
1

我有一個字典和格式是使用計算字典鍵和類型錯誤

key1: [list of number] 

key2: [list of number] 

等...

鍵是一個數,其中KEY1 < KEY2 <等...

我我試圖選擇所有最後的n列表,我想計算它。

x = 0 

for something in dict: 
    if something >= max(dict.keys()) - n: 
     x += sum(dict[something]) // len(dict[something]) 

,但我得到:

TypeError: unsupported operand type(s) for -: 'str' and 'int' 
and it said the error come from the 'if something >= max(dict) - n:' 

請幫助...

+0

你需要在你的例子中更具體一些。看看如何製作[mcve]。 –

回答

0

你似乎有不匹配的類型。例如,假設您有以下表達式

1 - '1' 

Python將正確地抱怨。

TypeError: unsupported operand type(s) for -: 'int' and 'str' 

因爲第一個操作數是整數,而seconde是一個字符串。

而且記住,

dict = {'1':[1,2,3,5,6], '2':[7,8,9,10,11]} 

是不一樣的

dict = {1:[1,2,3,5,6],2:[7,8,9,10,11]} 

在第一種情況下的鍵是字符串類型的,並在該Seconde系列是整數。

使用你的代碼,你可以測試它

type(max(dict.keys()))將輸出str將在其Seconde系列將輸出int

因此,您的操作數沒有相同的類型,它們都必須是整數才能繼續計算。我在詢問錯誤來自max(dict.keys()) - n。您應該仔細檢查dict的聲明(密鑰)。