You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算列表中各元素占总数的百分比(Python投票统计场景)

解决方法

先提前计算总票数,再在遍历候选人时动态计算得票百分比并格式化输出,同时优化胜负者的显示信息。修改后的完整代码如下:

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()

total_votes = sum(votes)  # 提前计算总票数,避免重复计算
print("Candidate\t Votes Received\t\t % of total votes")
for index, name in enumerate(names): 
    current_votes = votes[index]
    percentage = (current_votes / total_votes) * 100  # 计算当前候选人得票百分比
    # 格式化输出,保证姓名、票数、百分比对齐显示
    print(f"{name}\t\t {current_votes}\t\t\t {percentage:.2f}%")
print()
print("Total Votes:\t", total_votes)
print("Average votes:\t", mean(votes))
print()
# 找到最高得票对应的候选人并显示
winner_index = votes.index(max(votes))
print("Winner:\t\t", names[winner_index], f"({max(votes)} votes)") 
# 找到最低得票对应的候选人并显示
lowest_index = votes.index(min(votes))
print("Lowest Votes:\t", names[lowest_index], f"({min(votes)} votes)") 

核心修改点

  • 提前计算total_votes:避免循环中重复调用sum(votes),节省计算资源。
  • 动态索引获取票数:通过enumerate返回的index,直接取votes[index]拿到当前候选人的票数,实现索引动态化。
  • 百分比格式化:用{percentage:.2f}%将百分比格式化为两位小数的字符串,满足类似20.00%的显示需求。
  • 优化胜负者展示:不再只显示票数,而是对应显示候选人姓名,结果更直观。

内容的提问来源于stack exchange,提问作者wiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:31:12