Reputation: 486
I have got float values in s
:
p = list(swn.senti_synsets(a))
s = p[0].pos_score()
print(s)
# Output
0.0
0.0
1.0
0.0
0.25
0.25
then I tried, print(sum(s))
which gives the error 'float' object is not Iterable.
how to do this ?
Solution: Strange that I found the answer myself, i dont know but putting the thing of a separate function worked. `
for x in token:
sum_pos=sum_pos+posCheck(x)
sum_neg=sum_neg+negCheck(x)
def posCheck(a):
p=list(swn.senti_synsets(a))
s = p[0].pos_score() return(s)`
def negCheck(a): p=list(swn.senti_synsets(a)) s = p[0].neg_score() return(s)
I couldn't sum up the list, but when I put the function with returntype, it returned the sum of the positive numbers. Thanks to all of you for trying to help.
Upvotes: 8
Views: 93462
Reputation: 79
To sum float from a list , one easy way is to use fsum
import math
l=[0.0, 0.0, 1.0, 0.0, 0.25, 0.25]
math.fsum(l)
Upvotes: 6
Reputation: 2161
def do(*args):
mylist_ = [float("{:.2f}".format(num)) for num in args]
result =(sum(mylist))
return result
print(do(23.32,45,67,54.27))
Result:
189.59
I hope this will help.
Upvotes: 0
Reputation: 107
It is because in your original code, s
is not iterable, and you can thus not use sum on a non-iterable object. If you were to add each value from s
into a list, you could sum the list to give you the result you are looking for.
Not sure the function pos_score()
function works, but perhaps you can create and return the list result from that function?
Upvotes: 0
Reputation: 1213
Try this:
It adds all pos_score()
to a list, and then prints the sum.
p = list(swn.senti_synsets(a))
s = [x for x in p[0].pos_score()]
print(sum(s))
Upvotes: 0
Reputation: 808
values = [0.0, 0.0, 1.0, 0.0, 0.25, 0.25]
print sum(values)
works fine for me
Upvotes: 3
Reputation: 3223
You can also use:
>>> l=[0.0, 0.0, 1.0, 0.0, 0.25, 0.25]
>>> sum(map(float,l))
1.5
As other said, sum(l)
will also work. I don't know why you are getting error with that.
One possible reason might be that your list is of string data type. Convert it to float as:
l = map(float, l)
or
l = [float(i) for i in l]
Then using sum(l)
would work properly.
EDIT: You can convert the s
into list and then sum it.
s = p[0].pos_score()
print sum(list(s))
Upvotes: 3