Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of float numbers in a list in Python

Tags:

python

sum

nltk

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.

like image 859
Swarup Rajbhandari Avatar asked Jul 02 '15 14:07

Swarup Rajbhandari


People also ask

How do you add a number to a float list?

Use the list. append() method to add a float to a list in Python, e.g. my_list. append(3.3) . The list.

How do you sum data in a list in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

How do you sum a variable value in Python?

Use sum() to approach common summation problems. Use appropriate values for the iterable and start arguments in sum() Decide between sum() and alternative tools to sum and concatenate objects.


3 Answers

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))
like image 134
Rakholiya Jenish Avatar answered Sep 19 '22 09:09

Rakholiya Jenish


values = [0.0, 0.0, 1.0, 0.0, 0.25, 0.25]

print sum(values)

works fine for me

like image 36
Dportology Avatar answered Sep 21 '22 09:09

Dportology


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)
like image 23
SprigganCG Avatar answered Sep 18 '22 09:09

SprigganCG