Repeated assignments - a more elegant approach (newbie)
ajw126 at NOSPAMyork.ac.uk
Thu Jun 5 20:56:05 CEST 2003
> 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,
> if var > 0:
> mean += var
> count += 1
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:
is a bit shorter, but still not very nice. I'd go with David Eppstein said
if at all possible.
Anyway, hope this helps,
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