Repeated assignments - a more elegant approach (newbie)

David Eppstein eppstein at ics.uci.edu
Thu Jun 5 14:23:20 EDT 2003


In article <67e2f348.0306050942.62aa6074 at posting.google.com>,
 ivan.nazarenko at uol.com.br (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

The obvious thing to do is to replace your large number of separate 
variables mnx, cntx, etc with three lists.  Also spell out your variable 
names rather than making cryptic abbreviations for them

instead of a variable 'x' use value[i]
instead of a variable mnx use mean[i]
instead of a variable cntx use count[i]

then you could just do

for i in range(len(value)):
    if value[i] > 0:
        mean[i] += value[i]
        count[i] += 1

You could also use dictionaries instead of lists if you prefer them to 
be keyed by strings instead of integers.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list