2016-11-28 88 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

相关问题