![](/img/trans.png)
[英]How do i calculate the percentage increase or decrease in a list of values with python
[英]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.