wiro
wiro

Reputation: 138

How do I calculate a percentage of total for any and all elements in a list?

from statistics import mean
names = []
votes = []

numCandidates = 5

for candidate in range(numCandidates):
    names.append(input("Enter Candidate {0}'s last name: ".format(candidate + 1))) 
    votes.append(int(input("Enter Candidate {0}'s amount of votes: ".format(candidate + 1)))) 

print()

print("Candidate\t Votes Received\t\t % of total votes")
for index,name in enumerate(names): 
    print(name,"\t\t",votes[index])
print()
print("Total Votes:\t",sum(votes))
print("Average votes:\t",mean(votes))
print()
print("Winner:\t\t",max(votes)) 
print("Lowest Votes:\t",min(votes)) 

I have the user create input to two lists, one for names and one for amount of votes. I then enumerate the lists to give the appearance of a table:

Candidate        Votes Received          % of total votes
name1            5000
name2            3000
name3            4000
name4            7000
name5            6000

Total Votes:     25000
Average votes:   5000

Winner:          7000
Lowest Votes:    3000

Now, I'd like the % of total to display a percentage of total, for example for name1 the output should be 20.00%.

I believe I need something like votes.index[1] / sum(votes) but I don't know how to make the index "dynamic".

How can I achieve this?

Upvotes: 0

Views: 179

Answers (1)

wiro
wiro

Reputation: 138

Thanks @fsimonjetz for nudging to the correct answer.

I ended up adding this to the for loop:

round((votes[index]/sum(votes)*100),2),"%"

As such turning it into:

for index,name in enumerate(names): # need to add titles to columns
    print(name,"\t\t",votes[index],"\t\t\t",round((votes[index]/sum(votes)*100),2),"%")

Upvotes: 1

Related Questions