我正在尝试更正一个累积列表的代码。
到目前为止,我发现的代码可以做到这一点,但我想让它与字母一起工作,例如。
累加(“a”、“b”、“c”)
会变成a,ab,abc。

def accumulate(L):
    theSum = 0
    for i in L:
        theSum = theSum + i
        print(theSum)
    return theSum

accumulate([1, 2, 3])

最佳答案

虽然@willemvanonsem为您提供了一种可行的方法,但要缩短代码长度,您可以使用标准库中的itertools.accumulate

>>> from itertools import accumulate
>>>
>>> for step in accumulate(['a', 'b', 'c']):
    print(step)


a
ab
abc
>>>

10-04 10:55