请帮助更正我的Python基础代码:';对于';循环列表和累积和
就这些。感谢您通过打印出[1,3,4,10]的答案使其工作 改进您的解决方案,这里不需要2个for循环:请帮助更正我的Python基础代码:';对于';循环列表和累积和,python,loops,Python,Loops,就这些。感谢您通过打印出[1,3,4,10]的答案使其工作 改进您的解决方案,这里不需要2个for循环: 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 l
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]
最好在此处使用生成器函数:
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]
或者在py3x中使用itertools.accumulate
:
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]
你不需要两个循环。以下是一个简单的程序解决方案:
In [2]: from itertools import accumulate
In [3]: list(accumulate([1,2,3]))
Out[3]: [1, 3, 6]
列表
是函数名称的错误选择,因为它会隐藏内置的列表
。您的问题是没有为每个新元素将j
重置为0
。也不鼓励使用l
作为变量名,因为在某些字体中它看起来像1
def running_sums(numbers):
result = []
total = 0
for n in numbers:
total = total + n
result.append(total)
return result
不要使用
sum
作为变量名。在这样一个小片段中,您可以一目了然地看到所有用法,并告诉您这不是库函数,但很公平。更改。感谢您的全面回答。令人惊讶的答案,尽管基于我不太简短的代码。非常感谢。我想你的意思是[1,3,6,10]
。
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