[Tutor] calculate percents of items in a list
Steven D'Aprano
steve at pearwood.info
Mon Sep 1 03:46:04 CEST 2014
Hello,
You seem to have deliberately set the Reply-To header for replies to go
back to you, instead of allowing them to go to the mailing list for
others to take part in the conversation. I don't know if that was you
personally, or just another sign of the major suckage that is Yahoo
mail, but either way I have honoured that request this time, but
normally replies to questions on the tutor mailing list should go to
the mailing list so that the others may learn.
More comments below, interleaved with your questions.
On Sun, Aug 31, 2014 at 10:28:32AM -0700, LN A-go-go wrote:
>
>
> What would be a better way to calculate percentages of items in a list?
> please....
>
> CountList = [9221382, 10374466, 5192905, 1710238, 3359]
> CL = [float(i) for i in CountList]
I really don't know why you convert the numbers into floats. There
doesn't seem to be any reason for that -- you can sum integer numbers
just as easily. If you insist on floats, why not just make them floats
in the first place?
CountList = [9221382.0, 10374466.0, 5192905.0, 1710238.0, 3359.0]
but that's silly. If they are meant to be *counts*, then you cannot have
a fraction of a count. Just keep them as ints.
> CL
> sum = CL[0] + CL[1] + CL[2] + CL[3] + CL[4]
Here you accidentally "shadow" the built-in sum() function. You
shouldn't do this unless you know what you are doing. Instead:
total = sum(CountList)
gives you the total you are after.
> import math
That's not used or needed.
> perList = []
> n = 0
> def percentage(CL,sum):
> for i in CL:
> PER = "return 100 * float (CL[0])/float (sum)"
> perList.append(PER)
> n = n + 1
You appear to be wanting to calculate cumulative percentages. A simple
example:
CountList = [5, 2, 8, 5]
total = 20
cumulative percentages = [25.0, 35.0, 75.0, 100.0]
Is that correct? If so, this will do it:
counts = [9221382, 10374466, 5192905, 1710238, 3359]
cumulative_totals = []
last = 0
for value in counts:
last += value
cumulative_totals.append(last)
total = sum(counts)
# check that the last value matches the total:
assert total == cumulative_totals[-1]
cumulative_percentages = []
for value in cumulative_totals:
perc = value*100.0/total
cumulative_percentages.append(perc)
print(cumulative_percentages)
I think that should do the trick.
--
Steven
More information about the Tutor
mailing list