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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With