Repeated assignments - a more elegant approach (newbie)

Andrew Wilkinson ajw126 at NOSPAMyork.ac.uk
Thu Jun 5 20:56:05 CEST 2003


ivannaz wrote:

> Suppose I have the following code:
> 
> if a > 0:
>     mna += a
>     cnta += 1
> if b > 0:
>     mnb += b
>     cntb += 1
> if c > 0:
>     mnc += c
>     cntc += 1
> ... and so on, until 'z'
> 
> Is there a better way to write it? The idea would be something like
> (which obviously does not work):
> 
> for (var, mean, count) in [(a, mna, cnta), (b, mnb, cntb), (c, mnc,
> cntc)...]:
>     if var > 0:
>         mean += var
>         count += 1
> 
> Regards,
> 
> Ivan

If you really, really want to do it like that then...

for var in [chr(x) for x in range(97, 123)]:
    if eval(var) > 0:
        exec "mn"+var+"+="+var
        exec "cnt"+var+"+=1"

is a bit shorter, but still not very nice. I'd go with David Eppstein said
if at all possible.

Anyway, hope this helps,
Andrew Wilkinson

P.S.
I didn't actually run all of that, I couldn't be bothered setting up that
many variables :-) Should be pretty close to runnable though...




More information about the Python-list mailing list