listcomprehension, add elements?

John Machin sjmachin at lexicon.net
Sun Jun 22 19:39:44 EDT 2008


On Jun 23, 9:23 am, Paul Hankin <paul.han... at gmail.com> wrote:
> On Jun 23, 10:32 am, cirfu <circularf... at yahoo.se> wrote:
>
> > [a+b for a,b in zip(xrange(1,51), xrange(50,0,-1))]
>
> > [51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
> > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
> > 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51]
>
> > i want to add all the elemtns a s well. can i do this all in a
> > listcomprehension?
>
> > i can do this ofc:
> > reduce(lambda x,y:x+y,[a+b for a,b in zip(xrange(1,51),
> > xrange(50,0,-1))])
>
> > but reduce is a functional way of doing it, what is the more pythonic
> > way of doing this?
>
> Use the builtin 'sum' function.
>
> sum(a + b for a, b in zip(xrange(1, 51), xrange(50, 0, -1)))
>

Instead of sum(a + b for a, b in zip(foo, bar))
why not use sum(foo) + sum(bar)
?





More information about the Python-list mailing list