[Tutor] list comprehension problem

Emile van Sebille emile at fenx.com
Fri Jul 3 21:22:30 CEST 2009


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  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list