Python3遍历浮点数列表报错:'float'对象不可迭代求助
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
valueis 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 ensuringvalueis 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

