2016-11-28 129 views
0

我試圖解決認爲Python演習10.3的Python:類型錯誤: '詮釋' 對象不是可迭代(認爲Python 10.3)

Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6] .

我得到一個TypeError與此代碼:

def culm_sum(num): 
    res= [] 
    a = 0 
    for i in num: 
     a += i 
     res += a 
    return res 

當我打電話culm_sum([1, 2, 3])我得到

TypeError: 'int' object is not iterable 

謝謝!

+0

退房此線程,它有不止一個答案您的問題 http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python –

回答

3

您使用追加到列表中的代碼不正確:

res += a 

而是做

res.append(a) 

這有什麼錯res += a? Python所預期a是迭代和幕後試圖做等價的:

for item in a: 
    res.append(a) 

但由於a不迭代,所以你得到一個TypeError

注意我最初認爲你的錯誤是在for i in num:,因爲你的變量名稱很差。這聽起來像是一個整數。由於它是一個數字列表,至少使其複數(nums),以便您的代碼的讀者不會感到困惑。 (您通常會幫助的讀者是未來您。)

+1

嗨,感謝您的建議和您的編輯我的文章!之前沒有看到!它現在有效!也感謝您對變量名稱的建議! – trig

0

您正在嘗試執行的操作是extend您的列表中有一個int,這是不可迭代的,因此也是錯誤。你需要的元素使用append方法添加到列表:

res.append(a) 

這一點,正確的方法或者說,到extend

res += [a] 
+0

在我的回答中,我沒有提到'res + = [a]',因爲當存在另一個簡單的替代方案時,不必要地創建臨時對象是一種壞習慣。 –

+0

感謝您對[a]的建議。這也適用! – trig

相關問題