pythoncountiteritems

Counter and for loops


I am writing a piece of code that iterates through each record and prints a statistic called intervals.

for record in records:

    from collections import Counter
    count = Counter(intervals)

    for interval, frequency in count.iteritems():
        print interval
        print frequency

The output looks like this:

Record 1
199
7
200
30

Record 2
199
6
200
30

In this example, in Record 1, there are 7 instances of the interval length 199 and 30 instances of the interval length 200. In Record 2, there are 6 instances of the interval length 199 and 31 instances of the interval length 200. I would like to see the overall stat summary of both records like this but cannot figure out how to get these results:

All Records

199
13

200
61

Where in both records, there are 13 instances total of interval length 199 (7+6) and 61 instances total of interval length 200 (30+31). I am having trouble getting the overall statistic summary of my records as shown above.


Solution

  • You need variable outside for loop that store the frequency counting Following example may help you.

    from collections import Counter
    
    
    records = [[199,200,200], [200,199,200]]
    freq_dist = Counter()                        # Variable store frequency distribution
    
    for record in records:
        counts = Counter(record)
        freq_dist.update(counts)
    
    for freq, value in freq_dist.items():
       print(freq, value)
    

    Output:

    200 4
    199 2
    

    Reference collections.Counter