How Can I Use Sum() Function For A List In Python?
Solution 1:
The problem is that when you read from the input, you have a list of strings. You could do something like that as your second line:
numlist = [float(x) for x in numlist]
Solution 2:
The problem is that you have a list of strings. You need to convert them to integers before you compute the sum. For example:
numlist = numlist.split(",")
numlist = map(int, numlist)
s = sum(numlist)
...
Solution 3:
You are adding up strings, not numbers, which is what your error message is saying.
Convert every string into its respective integer:
numlist = map(int, numlist)
And then take the average (note that I use float()
differently than you do):
arithmetic_mean = float(sum(numlist)) / len(numlist)
You want to use float()
before dividing, as float(1/2) = float(0) = 0.0
, which isn't what you want.
An alternative would be to just make them all float
in the first place:
numlist = map(float, numlist)
Solution 4:
Split returns you an array of strings, so you need to convert these to integers before using the sum function.
Solution 5:
You can try this.
reduce(lambda x,y:x+y, [float(x) for x in distance])
Post a Comment for "How Can I Use Sum() Function For A List In Python?"