Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any way to tackle float Counter values in python

Tags:

python

I was writing a program for averaging some values. Details: I was having a folder and within which I got many .txt files with float numbers.
All I was doing is summing up the float values and storing them in a Counter for each files.
After that I want to add up all values in the Counter and divide them by total no. of files(i.e..txt).

But up to storing in a Counter goes fine, but when I want add up the values present in the Counter by using sum(Counter.values()) then it raises an error showing 'float' object has no attribute 'values'
I have gone through the manuals also, they are also saying it is possible for integer values.
But is there any was to add up float values within a counter.

like image 567
Ovisek Avatar asked Dec 07 '22 14:12

Ovisek


2 Answers

Why are you using a Counter object for summing values in files? Its stated purpose is "for counting hashable objects" (i.e. if you have multiple discrete objects that you want to count instances of).

If you want to store a sum floating point values from each file, try a regular dictionary:

floatsums = {}
floatsums['file1.txt'] = ... // insert code to sum the floats

total = sum(floatsums.values())
numfiles = len(floatsums)
like image 174
vergenzt Avatar answered Dec 21 '22 16:12

vergenzt


Despite what the documentation says, it works perfectly well to put float values into a Counter. Try it yourself.

    from collections import Counter

    a = Counter()
    a['a'] += 1
    a['a'] += 0.1
    a['b'] += 0.1
    print(list(a.items()))

In Python 3, at least. This gives

    [('a', 1.1), ('b', 0.1)]

This works in both Python 2 and 3. Of course, since this isn't what the documentation says, it's technically undefined behavior, so it may not work in future versions, but I doubt it. Still, if you want to be completely specs-compliant, you can do this:

    from collections import defaultdict

    a = defaultdict(float)

This will give you the same result as above and only uses documented features.

like image 30
Joel Croteau Avatar answered Dec 21 '22 16:12

Joel Croteau