2017-07-24 82 views
3

我正在尝试积累一个积累列表的代码。 到目前为止我已经发现的代码确实如此,但我希望使用字母,积累(“a”,“b”,“c”) 会成为a,ab,abc。用字母积累列表

def accumulate(*args): 
    theSum = '' 
    for i in args: 
     theSum += i # we can here shorten it to += (kudos to @ChristianDean) 
     print(theSum) 
    return theSum

此外,如果你想使用的参数的任意号码,你应该:

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

accumulate([1, 2, 3]) 
+0

只是声明'theSum'为空字符串:'theSum的= “”' – zwer

+0

@zwer迂腐鸡蛋里挑骨头,但不是一个宣言 - Python没有*有*变量声明。 –

+0

@ juanpa.arrivillaga - 公平点,但为时尚晚......'s/declare/initialize /'。 – zwer

回答

2

虽然@WillemVanOnsem已为您提供的方法这将起作用,缩短您的代码,您可以使用标准库中的itertools.accumulate

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


a 
ab 
abc 
>>> 
2

如果你想让它与字符串的工作,你必须一个空字符串初始化使用*args(或*L)。

现在当然这不再适用于数字。 theSum += i这里theSum = theSum + i的简称(因为字符串是不可变的)。但请注意,这是而不是始终是这种情况:对于列表,例如有一个区别。

现在它打印:

>>> accumulate("a", "b", "c") 
a 
ab 
abc 
'abc' 

最后'abc'不是print(..)语句的结果,但它是accumulate功能的return

+0

另请注意'theSum = theSum + i'可以缩短为'theSum + = i'。 –

+0

@ChristianDean:是的。添加到答案:)。 –

2

你可以试试这个:

import string 

l = string.ascii_lowercase 

the_list = [] 

letter = "" 

for i in l: 
    letter += i 
    the_list.append(letter) 

与发电机的功能更妙的是:

def accumulation(): 
    l = string.ascii_lowercase 
    letter = "" 
    for i in l: 
     letter += i 
     yield letter 

the_letters = list(accumulation()) 
print(the_letters) 

输出:

['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefg', 'abcdefgh', 'abcdefghi', 'abcdefghij', 'abcdefghijk', ...]