简体   繁体   English

如何计算列表中任何和所有元素的总数百分比?

[英]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% .现在,我希望占总数的百分比显示占总数的百分比,例如对于name1应该是20.00%

I believe I need something like votes.index[1] / sum(votes) but I don't know how to make the index "dynamic".我相信我需要像votes.index[1] / sum(votes)这样的东西,但我不知道如何使索引“动态”。

How can I achieve this?我怎样才能做到这一点?

Thanks @fsimonjetz for nudging to the correct answer.感谢@fsimonjetz 提出正确答案。

I ended up adding this to the for loop:我最终将其添加到 for 循环中:

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),"%")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM