如何计算列表中各元素占总数的百分比(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
相关产品推荐
相关产品推荐

