Repeated assignments - a more elegant approach (newbie)

ivannaz ivan.nazarenko at uol.com.br
Fri Jun 6 16:38:03 EDT 2003


David Eppstein <eppstein at ics.uci.edu> wrote in message 
> > 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'
> > 

> 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.

Thank you all for the answers. The vars names are not quite mna, mnt,
etc, but actually name of different instruments whose data are being
averaged. The idea of a dictionary seems cool, as well as simply
making an ordinary list.




More information about the Python-list mailing list