Reputation: 1
I have a list that changes within a for loop. This is an example of one of the lists:
lst = ['1.50%', '2.67%']
I want to be able to take the sum of this list and the length so that I can find the average. I performed the following operation:
sum(lst)/len(lst)
When printed, I receive an error.
I am wondering if I can take the percentage out of every input in the list, convert it to an integer, and execute the preceding function once more to see if it works.
How should I go about doing this? Also, if there is an easier way, how should I proceed with such a step?
Upvotes: 0
Views: 69
Reputation: 1019
try this code:
lst = ['1.50%', '2.67%']
lst2=[]
for i in lst:
lst2.append(float(i[0:-1]))
print(sum(lst2)/len(lst2))
Upvotes: 0
Reputation: 1122252
You need to strip the percent sign and convert the remainder to float, as you cannot meaningfully sum strings:
sum(float(v.rstrip('%')) for v in lst) / len(lst)
Demo:
>>> lst = ['1.50%', '2.67%']
>>> sum(float(v.rstrip('%')) for v in lst) / len(lst)
2.085
Upvotes: 4