Assigning a variable based on a lists conditions

Viewed 25

I'm creating a simple data input program for a PPC Campaign (SEO) that uses averages.

The averages of the data when diving the total amount will change if the value is entered as == 0.

For example (1+2+3+0)/4 = Average

I'm trying to write my code when a 0 is entered the number dividing will reduce the total list amount to exclude any variables that are 0.

For example (1+2+3+0)/3 = Average.

I'm stumped on how to create this. I'll emphasis the section of code where this would take place.

Thankyou!

Here is a copy of my code:

   Artlist = [Ac,Rooter,Plumbing,Electric,Leaks,Water,pspent]

   average = sum(Artlist)/7
2 Answers
a = [6,7,9,15,0,69,44,360,8,0.0,6,0,]
b= list(filter(lambda x: (x!= 0), a))
avg = sum(a)/len(b)
print(avg)

or

Artlist = [Ac,Rooter,Plumbing,Electric,Leaks,Water,pspent]
non_zero_val = list(filter(lambda x: (x!= 0), Artlist))
average = sum(Artlist)/len(non_zero_val)

Used above example for your problem

If you have access to numpy, you can use its count_nonzero function to (do I really have to say it?) get the count of the non-zero elements, which you can divide your sum by to get your average.

Related