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 usually do this:

>>> histogram = {}
>>> for i in range(1,7):
        for j in range(1,7):
                s = i + j
                if histogram.has_key(s):
                        histogram[s] += 1
                else:
                        histogram[s] = 1

>>> for i in histogram:
        print i,histogram[i]

2 1
3 2
4 3
5 4
6 5
7 6
8 5
9 4
10 3
11 2
12 1

Note that only results actually encountered create dictionary
entries, so there is no result for index 0 or 1. 

> 
> Thanks,
> THN

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to