def Cumulative(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]
return cu_list[1:]
# Driver Code
lists = [10, 20, 30, 40, 50]
print (Cumulative(lists))
任何人都可以帮助我扩展列表理解能力吗?
我已经写了这段代码
def cum_sum(m):
result = 0
for x in m:
result += x
print(result, end=", ")
cum_sum([1,2,3,10])
使用发电机
def cum_sum(m):
result = 0
for x in m:
result += x
yield result
list(cum_sum([1,2,3,10]))
如果您想在没有列表理解的情况下进行操作,则可以按照以下方式进行操作
def Cumulativex(lists):
cu_list = []
length = len(lists)
for x in range(0,length+1):
cu_list.append(sum(lists[0:x]))
return cu_list[1:]
print(Cumulativex(lists))
两者的结果与[10, 30, 60, 100, 150]
相同