Repeated assignments - a more elegant approach (newbie)

Steven Taschuk staschuk at telusplanet.net
Thu Jun 5 20:33:38 CEST 2003


Quoth ivannaz:
> 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? [...]

Yes; don't use a bunch of names, use data structures such as lists:

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

Or some such.

-- 
Steven Taschuk                           staschuk at telusplanet.net
"I'm always serious, never more so than when I'm being flippant."
                            -- _Look to Windward_, Iain M. Banks





More information about the Python-list mailing list