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 <[email protected]>
To: [email protected]
Subject: Re: [Tutor] list comprehension problem
Message-ID: <[email protected]>
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
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to