Thomas Nelson wrote: > I have this code: > type1 = [0] > type2 = [0] > type3 = [0] > map = {0:type1, 1:type1, 2:type3, 3:type1, 4:type2} # the real map is > longer than this > > def increment(value): > map[value][0] += 1 > > increment(1) > increment(1) > increment(0) > increment(4) > #increment will actually be called many times through other functions > print type1[0], type2[0], type3[0] > #should print "3 1 0" > > This is exactly what I want to do: every time I encounter this kind of > value in my code, increment the appropriate type by one. Then I'd like > to go back and find out how many of each type there were. This way > I've written seems simple enough and effective, but it's very ugly and > I don't think it's the intended use of lists. Does anyone know a > cleaner way to have the same funtionality?
I don't think your code is ugly. Anyway, here are two more alternatives: >>> types = [0] * 3 >>> dispatch = [0, 0, 2, 0, 1] >>> for value in [1, 1, 0, 4]: ... types[dispatch[value]] += 1 ... >>> types [3, 1, 0] >>> inflated = [0] * 5 >>> groups = [[0, 1, 3], [4], [2]] >>> for value in [1, 1, 0, 4]: ... inflated[value] += 1 ... >>> [sum(inflated[i] for i in group) for group in groups] [3, 1, 0] Peter -- http://mail.python.org/mailman/listinfo/python-list