Hi, How do I sum all occurrences of a number in a file?
I have a file with a bunch of numbers, each on it's own line:

5
3
11
3
7
3
5
5
11
7
7
...
How do i sum them up so that the output will be ,
5 : 15
3 : 9
11: 22
7 : 21

4
Contributors
8
Replies
10
Views
7 Years
Discussion Span
Last Post by pyTony

The easiest way is to use Python's count() function (and then test for a result > 0) for smaller groups of numbers. Some info on using lists. A list can also be used by element or index number. Element[0] = the number of zeros found, element[1] = number of ones, etc. which can then be multiplied by the element/index number to get the result. You can also use a dictionary, with the key equal to the number, pointing to an integer that counts the number of times the number appears.

``````number_list = [5, 3, 11, 3, 7, 3, 5, 5, 11, 7, 7 ]
for num in range(12):
print "%d:%d:%d" % (num, number_list.count(num), num*number_list.count(num))``````

Edited by woooee: n/a

But i want the file to call out the numbers, instead of a list

For Python 3/2.7 solution this is simplest:

``````from collections import Counter
print(Counter(line.rstrip() for line in open('data.txt')))``````

Edited by pyTony: n/a

Duplicate post deleted. This seems to be duplicate post day.

Edited by woooee: n/a

Hi,
I was trying to do the same thing but with strings. Here is my code:

``````lis=['a','a','a','b','b','d','d','f']
for char in lis:
print(char,":",lis.count(char))``````

The problem I'm facing is that the code above outputs the frequency for all duplicate items too. So, it shows

a:3
a:3
a:3
..and so on.

How do I solve this problem? Thanks

I think I figured out how to avoid the problem I mentioned above. For those who would be interested, I've used a dictionary to store the frequency. Here's the final code-

``````lis=['a','a','a','b','b','d','d','f']
diction={}
for char in lis:
diction[char]=lis.count(char)
print (diction)``````

You can iterate over set of the letters in list. Or you can avoid repeated reading of list by iterating all letters and adding the count of letters.