繁体   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)) 

我让用户创建两个列表的输入,一个用于名称,一个用于投票数量。 然后我枚举列表以给出表格的外观:

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

现在,我希望占总数的百分比显示占总数的百分比,例如对于name1应该是20.00%

我相信我需要像votes.index[1] / sum(votes)这样的东西,但我不知道如何使索引“动态”。

我怎样才能做到这一点?

感谢@fsimonjetz 提出正确答案。

我最终将其添加到 for 循环中:

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

这样把它变成:

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