Augmented Assignment question
Bob Gailer
bgailer at alum.rpi.edu
Wed Jul 16 18:52:29 EDT 2003
At 06:13 PM 7/16/2003 +0000, Doug Tolton wrote:
>I have a function that returns a tuple:
>
> def checkdoc(self, document):
> blen = document['length']
> bates = document['obates']
>
> normal, truncated, semicolon = 0,0,0
> for bat in bates:
> if len(bat) == 2 * blen:
> semicolon += 1
> if len(bat) == blen - 1:
> truncated += 1
> if len(bat) == blen:
> normal += 1
>
> return normal, truncated, semicolon
>
>on the other side I have 3 variables:
>normal, truncated and semicolon
>
>I would like to be able to do an augmented assignment such as:
>
>normal, truncated, semicol += self.checkdoc(mydoc)
>
>however this returns the following error:
>SyntaxError: augmented assign to tuple not possible
>
>I did some reading and it seems that an augmented assignment is
>specifically verboten on tuples and lists. Is there a clean way to
>accomplish this? I dislike in the extreme what I've resorted to:
>
>fnormal, ftruncated, fsemicolon = 0,0,0
>
>// loop through a file and process all documents:
> normal, truncated, semicolon = self.checkdoc(curdoc)
> fnormal += normal
> ftruncated += truncated
> fsemicolon += semicolon
>
>This solution strikes me as inelegant and ugly. Is there a cleaner
>way of accomplishing this?
I suggest: use a list instead of separate counter variables, and update the
list within the function.
counters = [0]*4 # initialize list
def checkdoc(self, document, counters):
blen = document['length']
bates = document['obates']
for bat in bates:
if len(bat) == 2 * blen:
x = 0
if len(bat) == blen - 1:
x = 1
if len(bat) == blen:
x = 2
else:
x = 3 #
counters[x] += 1
Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003
More information about the Python-list
mailing list