[Tutor] list comprehension problem

Dinesh B Vadhia dineshbvadhia at hotmail.com
Fri Jul 3 21:49:30 CEST 2009


d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1]

and we want:

[0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96]


dd = [ sum(d[:j]) for j in range(len(d)) ][1:]

gives:

[0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95]

Dinesh


--------------------------------------------------------------------------------

Message: 6
Date: Fri, 03 Jul 2009 12:22:30 -0700
From: Emile van Sebille <emile at fenx.com>
To: tutor at python.org
Subject: Re: [Tutor] list comprehension problem
Message-ID: <h2llpn$9db$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 7/3/2009 12:09 PM Dinesh B Vadhia said...
> I'm suffering from brain failure (or most likely just being brain less!) 
> and need help to create a list comprehension for this problem:
>  
> d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 
> 1, 6, 3, 5, 6, 11, 1]
>  
> Want to create a new list that adds the current number and the prior 
> number, where the prior number is the accumulation of the previous 
> numbers ie.

[ sum(d[:j]) for j in range(len(d)) ][1:]

Emile

>  
> dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 
> 84, 95, 96]
>  
> A brute force solution which works is:
>  
>  >>> dd = []
>  >>> y = d[0]
>  >>> for i, x in enumerate(d):
>  >>>        y += x
>  >>>        dd.append(y)
>  
> Is there a list comprehension solution?
>  
> Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090703/2f2c6b25/attachment.htm>


More information about the Tutor mailing list