I'm trying to get the average of values from the num list
let's say I have Input
list1 = [0, 2, 2, 0 ]
list2 = [5, 10, 5, 0]
The output should be :
list1_output = [0, 50, 50, 0 ]
list2_output = [25, 50, 25, 0]
The purpose is to represent the input as percentage in the Chart.
In my case, len
of the list
will always be going to be 4, and the sum
of input can increase from 100 but the sum
of output should never be more than 100.
Can anybody give me any idea how I can approach this using python? Sudo code also will be helpful.
CodePudding user response:
You can do that with a list comprehension:
sum1 = sum(list1)
[i/sum1*100 for i in list1]
Output:
[0.0, 50.0, 50.0, 0.0]
CodePudding user response:
You can compute the sum of all elements and divide each element by the sum.
list1 = [0, 2, 2, 0 ]
list2 = [5, 10, 5, 0]
def prcnt(lst):
sm = sum(lst)
return [int((l/sm)*100) for l in lst]
print(prcnt(list1))
print(prcnt(list2))
[0, 50, 50, 0]
[25, 50, 25, 0]