这里有一个足够强大的函数,适用于任何支持
+
的对象可迭代,并且适用于从2.3版本开始的任何Python(只需调整
print
和
xrange
以使测试基础设施与3.x兼容):
Python 2.3.5 (
Type "help", "copyright", "credits" or "license" for more information.
>>> def cumsum(iterable):
... first = True
... for v in iterable:
... if first:
... tot = v
... first = False
... else:
... tot = tot + v
... yield tot
...
>>> def squares(start, stop):
... for i in xrange(start, stop):
... yield i * i
...
>>> tests = [
... [],
... [1],
... [1, 2],
... range(7),
... (0, 1, 2, 3, 4, 5, 6),
... ['a', 'b', 'c'],
... [['a'], ['b'], ['c']],
... (('a', ), ('b', ), ('c', )),
... squares(1, 5),
... ]
>>>
>>> for test in tests:
... print test, list(cumsum(test))
...
[] []
[1] [1]
[1, 2] [1, 3]
[0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 6, 10, 15, 21]
(0, 1, 2, 3, 4, 5, 6) [0, 1, 3, 6, 10, 15, 21]
['a', 'b', 'c'] ['a', 'ab', 'abc']
[['a'], ['b'], ['c']] [['a'], ['a', 'b'], ['a', 'b', 'c']]
(('a',), ('b',), ('c',)) [('a',), ('a', 'b'), ('a', 'b', 'c')]
<generator object at 0x014B6A58> [1, 5, 14, 30]
>>>