Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #47362

Re: Idiomatic Python for incrementing pairs

References <20130607213239.3e39a448@bigbox.christie.dr>
Date 2013-06-07 23:46 -0400
Subject Re: Idiomatic Python for incrementing pairs
From Jason Swails <jason.swails@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2871.1370663190.3114.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Fri, Jun 7, 2013 at 10:32 PM, Tim Chase <python.list@tim.thechases.com>wrote:

> Playing around, I've been trying to figure out the most pythonic way
> of incrementing multiple values based on the return of a function.
> Something like
>
>   def calculate(params):
>     a = b = 0
>     if some_calculation(params):
>       a += 1
>     if other_calculation(params):
>       b += 1
>     return (a, b)
>
>   alpha = beta = 0
>   temp_a, temp_b = calculate(...)
>   alpha += temp_a
>   beta += temp_b
>
> Is there a better way to do this without holding each temporary
> result before using it to increment?
>

alpha = beta = 0
alpha, beta = (sum(x) for x in zip( (alpha, beta), calculate(...) ) )

It saves a couple lines of code, but at the expense of readability IMO.  If
I was reading the first, I'd know exactly what was happening immediately.
 If I was reading the second, it would take a bit to decipher.  In this
example, I don't see a better solution to what you're doing.

All the best,
Jason

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Idiomatic Python for incrementing pairs Jason Swails <jason.swails@gmail.com> - 2013-06-07 23:46 -0400

csiph-web