我试图得到[1,3,6]作为结果.我错过了一些非常明显的东西吗 我得到的错误是:IndexError: list index out of range
def cumulative_sum(n):
cum_sum = []
y = 0
for i in n:
y += n[i]
cum_sum.append(y)
print cum_sum
a = [1,2,3]
cumulative_sum(a)
Run Code Online (Sandbox Code Playgroud)
def cumulative_sum(n):
cum_sum = []
y = 0
for i in n: # <--- i will contain elements (not indices) from n
y += i # <--- so you need to add i, not n[i]
cum_sum.append(y)
print cum_sum
a = [1,2,3]
cumulative_sum(a)
Run Code Online (Sandbox Code Playgroud)
数组是从零开始的Python,所以当你迷茫n[i]与i你进行访问n[3],而n只能从0到2.
问题在于你的循环:
for i in n:
y += n[i]
Run Code Online (Sandbox Code Playgroud)
该for循环遍历值的n,而不是指标.更改y += n[i]到y += i.
在第三次通过循环时(当i为3时)引发异常,因为3不在数组的边界内(有效索引为[0-2]).
如果你想循环索引,你可以使用内置enumerate函数:
for i, x in enumerate(n):
assert n[i] == x
Run Code Online (Sandbox Code Playgroud)
这是一个简单的基于生成器的实现:
def cumsum(seq):
s= 0
for c in seq:
s+= c
yield s
print [c for c in cumsum(range(7))]
print [c for c in cumsum((0, 1, 2, 3, 4, 5, 6))]
Run Code Online (Sandbox Code Playgroud)
这是恕我直言,实施cumsum相当Pythonic的方式.
但这是一个更实用的实现,它允许您处理(最重要的)所有类型,其中添加可能有意义.
def cumsum(seq):
s= seq[0]
for k in xrange(1, len(seq)):
yield s
s= s+ seq[k]
yield s
print [c for c in cumsum(range(7))]
print [c for c in cumsum((0, 1, 2, 3, 4, 5, 6))]
print [c for c in cumsum(['a', 'b', 'c'])]
print [c for c in cumsum([['a'], ['b'], ['c']])]
print [c for c in cumsum((('a', ), ('b', ), ('c', )))]
Run Code Online (Sandbox Code Playgroud)
因此,所有这些示例都表现出预期的方式,而对于更多Pythonic版本则不然.自己尝试一下,找出不同行为的原因.
更新:
根据评论,更通用的cumsum将是:
def cumsum(iterable):
iterable= iter(iterable)
s= iterable.next()
yield s
for c in iterable:
s= s+ c
yield s
tests= [
[],
[1],
[1, 2],
range(7),
(0, 1, 2, 3, 4, 5, 6),
['a', 'b', 'c'],
[['a'], ['b'], ['c']],
(('a', ), ('b', ), ('c', )),
xrange(7),
]
for test in tests:
print test, '=> ', list(cumsum(test))
Run Code Online (Sandbox Code Playgroud)
仍有两个收益率,但恕我直言,它仍然非常可读.现在,实现的重点是iterable的第一个元素的类型决定了如何期望添加与其余元素的行为.