You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3遍历浮点数列表报错:'float'对象不可迭代求助

Fixing "TypeError: 'float' object is not iterable" in sum(value)

Hey there, let's break down this error you're hitting and get your code back on track!

What's causing the problem?

The sum() function in Python needs an iterable (like a list, tuple, or other collection of items) to loop through and add up values. But right now, your variable value is a single float number (think something like 3.14 or 7.8), which can't be "iterated over"—you can't loop through a single number, after all! That's why Python throws the error directly at your v = sum(value) line.

How to fix it

Let's cover common scenarios and quick fixes:

  • If you meant to sum a group of numbers: Double-check where value is defined before line 18. It's likely you accidentally overwrote it with a single float instead of keeping it as a list/tuple. For example, if you had a loop that was supposed to append values to a list but instead replaced the list with a single number, that's the culprit. Fix it by ensuring value is a collection:
    # Correct: value is a list of floats
    value = [2.5, 4.7, 1.3]
    v = sum(value)  # This works perfectly!
    
  • If you only have one float but still want to use sum() (though it's a bit unnecessary): Wrap the float in a list or tuple to make it iterable:
    value = 5.9
    v = sum([value])  # Wraps the float in a list, sum returns 5.9
    

Quick debugging tip

Add a quick print statement right before line 18 to confirm what value really is:

print(type(value))  # Should show <class 'list'> or <class 'tuple'>, not <class 'float'>
v = sum(value)

This will help you pinpoint exactly where value turned into a float instead of the collection you intended.

内容的提问来源于stack exchange,提问作者Daniel Galvan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:54:36