So I'm trying to add all the numbers of a list and divide that sum by how many numbers in that list are not equal to 0. The code does not include the part where I summed all the numbers together. What I did in this part of my code is that I tried to check each individual item in a list one at a time. Eventually, it would tell me how many numbers were not equal to zero with the variable sum_div.
b=4
c=0
d=6
e=0
I_list = [ b, c, d, e]
sum_div = 0
ip = I_list[0]
for i in range(0, len(I_list), 1) :
while ip != 0:
sum_div += 1
elif ip == 0:
sum_div += 0
print(sum_div)
sum_div was supposed to equal 2 in this case.
You can use a list comprehension to filter out the elements that are 0
then determine the len of that list. Then just divide the sum by that length to compute the average (of non-zero elements)
>>> sum(I_list) / len([i for i in I_list if i])
5.0
Technically you could also guard against an empty list, or a list of all zeroes
try:
average = sum(I_list) / len([i for i in I_list if i])
except ZeroDivisionError:
average = whatever_here # don't know what you'd want in this case
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments