请帮助纠正我的Python基础知识代码:'for'循环列表和累积总和

时间:2013-05-01 02:16:23

标签: python loops

enter code here
"""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]."""

def list(l):
 new_l = []
 j = 0
 for i in l:
   for i in range(l.index(i)+1):   
    j += l[i]
   new_l.append(j)  # this for loop seems to accumulate twice
 return new_l

print list([1,2,3,4]) # [1,4,10,20] other than [1,3,4,10]

就是这样。感谢您通过打印[1,3,4,10]来使其工作的答案!

3 个答案:

答案 0 :(得分:1)

改进您的解决方案,这里不需要2个for循环:

def lis(l):
 new_l = []
 j = 0
 for i in range(len(l)):
       j += l[i]
       new_l.append(j)
 return new_l

print lis([1,2,3,4])  #prints [1, 3, 6, 10]

最好在这里使用生成器功能:

def cumulative(lis):
    summ=0
    for x in lis:
       summ+=x
       yield summ
   ....:        

In [48]: list(cumulative([1,2,3]))
Out[48]: [1, 3, 6]

或在py3x中使用itertools.accumulate

In [2]: from itertools import accumulate

In [3]: list(accumulate([1,2,3]))
Out[3]: [1, 3, 6]

答案 1 :(得分:0)

您不需要两个循环。这是一个简单的程序解决方案:

def running_sums(numbers):
  result = []
  total = 0
  for n in numbers:
    total = total + n
    result.append(total)
  return result

答案 2 :(得分:0)

list是您的函数名称的错误选择,因为它会影响内置list。您的问题是,您没有为每个新元素重置j0。也不鼓励使用l作为变量名称,因为它在某些字体中看起来像1

def do_list(l):
    new_l = []
    for i in l:
        j = 0            # <== move this line here
        for i in range(l.index(i)+1):   
            j += l[i]
       new_l.append(j)
     return new_l

另一种看待它的方法是摆脱内部循环,每次只添加当前项目

def do_list(l):
    new_l = []
    j = 0           
    for i in l:
        j += i
        new_l.append(j)
    return new_l