简体   繁体   English

Python中列表中浮点数的总和

[英]Sum of float numbers in a list in Python

I have got float values in s :我在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.然后我尝试了print(sum(s))这给出了错误“浮动”对象不是可迭代的。 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.我无法总结列表,但是当我将函数放入 returntype 时,它​​返回了正数的总和。 Thanks to all of you for trying to help.感谢你们所有人的帮助。

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

print sum(values)

works fine for me对我来说很好用

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.正如其他人所说, sum(l)也将起作用。 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.然后使用sum(l)将正常工作。


EDIT: You can convert the s into list and then sum it.编辑:您可以将s转换为列表,然后将其求和。

s = p[0].pos_score()
print sum(list(s))

To sum float from a list , one easy way is to use fsum要从列表中对浮点数求和,一种简单的方法是使用 fsum

import math

l=[0.0, 0.0, 1.0, 0.0, 0.25, 0.25]
math.fsum(l)

Try this:试试这个:

It adds all pos_score() to a list, and then prints the sum.它将所有pos_score()添加到列表中,然后打印总和。

p = list(swn.senti_synsets(a))
s = [x for x in p[0].pos_score()]
print(sum(s))

It is because in your original code, s is not iterable, and you can thus not use sum on a non-iterable object.这是因为在您的原始代码中, s不可迭代,因此您不能在不可迭代的对象上使用 sum 。 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.如果您要将s每个值添加到列表中,您可以对列表求和以提供您正在寻找的结果。

Not sure the function pos_score() function works, but perhaps you can create and return the list result from that function?不确定函数pos_score()有效,但也许您可以从该函数创建并返回列表结果?

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.我希望这将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM