how can I avoid abusing lists?

Tim Chase python.list at tim.thechases.com
Fri Jul 7 13:22:30 EDT 2006


> Just forget the lists...
> 
> counters = {0:0, 1:0, 2:0, 3:0, 4:0}

You'll notice that the OP's code had multiple references to the 
same counter (0, 1, and 3 all mapped to type1)

The OP's method was about as good as it gets.  One might try to 
redo it with an accumulator class of some sort:

class Accumulator(object):
	def __init__(self, startvalue = 0):
		self.counter = startvalue
	def __iadd__(self, qty):
		self.counter += qty
		return self.counter
	def add(self, qty = 1):
		self.counter += qty
	def __int__(self):
		return self.counter
	def __str__(self):
		return str(self.counter)
	def __repr__(self):
		return '<Accumulator 0x%x (%s)>' % (
			id(self), str(self.counter))

type1 = Accumulator()
type2 = Accumulator()
type3 = Accumulator()
d = {0:type1, 1:type1, 2:type3, 3:type1, 4:type2}

print ','.join([str(x) for x in d.values()])
# all zeros
d[0] += 1
print ','.join([str(x) for x in d.values()])
# d[0], d[1], and d[3] have incremented
d[2].add()
d[2].add()
print ','.join([str(x) for x in d.values()])
# d[2] has now incremented twice
d[4].add(5)
print ','.join([str(x) for x in d.values()])
# d[4] has now incremented by 5

Some of the syntactic sugar of the class could likely be left out 
if you just want, but it does the same thing as the OP's, with a 
diff. spin on the syntax.

-tkc









More information about the Python-list mailing list