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

Recommended Answers

All 8 Replies

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))

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')))

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

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

If you can't print a simple list, then you want to start at the very beginning, since counting is more complicated than printing (which is a simple loop). Some links to on-line books
http://www.greenteapress.com/thinkpy...tml/index.html
http://diveintopython.org/toc/index.html
(see "Beginner's Guide" and "Python Books") http://wiki.python.org/moin/

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.