[Tutor] Summing up numbers in a file
Adam Bark
adam.jtm30 at gmail.com
Tue Oct 26 22:34:06 CEST 2010
On 26/10/10 21:20, masawudu bature wrote:
> 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
>
Assuming you know how to iterate through a file, you could try saving
the number of occurrences of each number in the file into a dictionary.
Something like:
if num in my_dict:
my_dict[num] += 1
else:
my_dict[num] = 1
HTH.
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101026/5ecc129e/attachment.html>
More information about the Tutor
mailing list