本文介绍了生成部分累积值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有以下清单:

l = [1,2,3,4]

和我想获得如下列表:

l_partial_sum = [1,3,6,10](即[1,1 + 2,1 + 2 + 3,1 +] 2 + 3 + 4])


有一种简单的方法可以实现这个目标吗?


我提出了以下解决方案,但似乎有点太了

详细说明了这个任务:

l_partial_sum = [reduce(lambda x,y:x + y,sub_l)for [1 [:i + 1]中的sub_l ]

我的范围(len(l))]]


任何帮助将不胜感激。


谢谢

Francesco

Hi,

I have the following list:
l = [1, 2, 3, 4]
and I''d like to obtain a list like the following:
l_partial_sum = [1, 3, 6, 10] (that is [1, 1+2, 1+2+3, 1+2+3+4])

Is there a simple way to accomplish this?

I came up with the following solution but it seems a bit too
elaborated for the task:
l_partial_sum = [reduce(lambda x,y:x+y, sub_l) for sub_l in [l[:i+1]
for i in range(len(l))]]

Any help will be appreciated.

Thanks
Francesco

推荐答案



[1,3,6,10]


- Bj?rnKempén

[1, 3, 6, 10]

- Bj?rn Kempén





谢谢,


实际上我的问题多了一点复杂(我以为我可以通过发布简化版本获得一个

解决方案......)


该列表由对象组成:

l = [obj1,obj2,obj3,obj4]

我需要在每个对象上调用一个方法(比如method1),如下所示:

l1 = [obj1 .method1(obj2),obj2.method1(obj3),obj3.method1(obj4),

obj4]


这样做有干净的方法?


再次感谢

Francesco

Thanks,

actually my problem is a bit more complex (I thought I could get a
solution by posting a simplified version...)

The list is composed of objects:
l = [obj1, obj2, obj3, obj4]
and I need to call a method (say method1) on each object as follow:
l1 = [obj1.method1(obj2), obj2.method1(obj3), obj3.method1(obj4),
obj4]

Is there a clean way of doing this?

Thanks again
Francesco


这篇关于生成部分累积值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 12:03