生成部分累积值的列表 [英] generate list of partially accumulated values

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

问题描述




我有以下清单:

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

推荐答案

9月16日上午11:56,cesco< fd。 calabr ... @ gmail.comwrote:
On Sep 16, 11:56 am, cesco <fd.calabr...@gmail.comwrote:




我有以下列表:

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 [l [: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


>> l = [1,2,3 ,4]
[sum(l [:x + 1])for x in xrange(len(l))]
>>l = [1, 2, 3, 4]
[sum(l[:x+1]) for x in xrange(len(l))]



[1,3,6,10]


- Bj?rnKempén

[1, 3, 6, 10]

- Bj?rn Kempén


呃。 ..结果很奇怪。


无论如何,这里再来一次


l = [1,2,3,4]
x b中的
[sum(l [:x + 1])(len(l))]

Uh... that turned out weird.

Anyways, here goes again

l = [1, 2, 3, 4]
[sum(l[:x+1]) for x in xrange(len(l))]


l = [1, 2,3,4
l = [1, 2, 3, 4]

[sum(l [:x + 1] ])for x in xrange(len(l))]
[sum(l[:x+1]) for x in xrange(len(l))]



谢谢,


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

解决方案......)


该列表由对象组成:

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


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆