浮点总和 - “浮点"对象不可迭代 [英] Sum of float - 'float' object is not iterable
问题描述
for match in matches:
p = float(match.split()[0])
print(p)
上面的代码给出了以下结果:
Code above gives the following result:
2.14
6.06
6.89
但是,如果我尝试将这些数字相加
However if I try to sum those numbers
print(sum(p))
我收到错误浮动"对象不可迭代
I receive an error 'float' object is not iterable
推荐答案
您基本上是在尝试取 p
的总和,这是一个 float
导致您的错误.如果您想要所有浮点数的总和,您应该将它们存储在一个结构中,然后对其求和:
You're basically trying to take the sum of p
, which is a float
ergo your error. If you want the sum of all the floats you should store them in a structure and then sum over that:
myFloats = [float(m.split()[0]) for m in matches]
print(myFloats)
print(sum(myFloats))
我在这里使用列表推导式将所有浮点数存储在列表中,但它与您的 for 循环执行相同的操作.如果您更喜欢使用 for 循环,您可以使用 myFloats.append
代替.或者,如果您只想对数据求和而不关心任何其他存储,那么您可以像这样使用 map
:
I used a list comprehension here to store all the floats in a list but it does the same thing as your for loop. If you'd prefer to use the for loop you can use myFloats.append
instead. Alternatively, if you just want to sum your data and don't care about any other storage then you can use map
like this:
print(sum(map(lambda x: float(x.split()[0]), matches)))
顺便说一句,将来为自己修复类似错误的一个好方法是使用 type
方法.Thsi 会告诉你变量的类型是什么.例如,print(type(p))
会返回float",这会告诉你你没有使用可迭代对象.
As an aside, a great way to fix similar errors for yourself in the future is to use the type
method. Thsi will tell you what the type of your variable is. For instance, print(type(p))
would return "float", which would've told you that you weren't working with an iterable.
这篇关于浮点总和 - “浮点"对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!