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

如何使用Python解析JSON实现候选人ID与姓名匹配及选票统计

问题解决方案

1. 原有代码问题说明

  • 候选人ID映射字典ids在循环内部初始化,每次遍历都会清空重置,最终只能保留最后一个候选人的映射关系
  • 选票统计逻辑错误,没有关联已有的ID映射关系,统计对象也不符合输入数据结构
  • 多余导入了未使用的numpy库

2. 修正后的实现代码

import json
from collections import Counter

# 加载JSON数据
with open('data.json', 'r', encoding='utf-8') as f:
    db = json.load(f)

# 解决问题1:构建候选人ID到姓名的映射表
id_to_name = {}
for candidate in db["candidates"]:
    # 仅保留状态有效的候选人
    if candidate["status"]:
        id_to_name[candidate["id"]] = candidate["name"]

# 解决问题2:选票统计实现(此处实现两种常用统计逻辑,可按需选择)
# 逻辑1:每张选票仅第一选择计票(普选制)
first_choice_votes = []
for vote in db["votes"]:
    # 跳过空选票
    if vote:
        first_choice_votes.append(vote[0])
vote_count = Counter(first_choice_votes)

# 输出统计结果
print("===== 选举结果(第一选择计票) =====")
for candidate_id, count in vote_count.most_common():
    print(f"候选人 {id_to_name[candidate_id]}:{count} 票")

# 逻辑2:偏好全统计(每张选票的所有选择各计1票,可选)
# all_votes = []
# for vote in db["votes"]:
#     all_votes.extend(vote)
# vote_count = Counter(all_votes)
# print("===== 选举结果(偏好全统计) =====")
# for candidate_id, count in vote_count.most_common():
#     print(f"候选人 {id_to_name[candidate_id]}:{count} 票")

3. 运行效果

使用你提供的data.json运行上述代码,第一选择计票的输出结果为:

===== 选举结果(第一选择计票) =====
候选人 Avia:2 票
候选人 Stan:2 票
候选人 Bob:2 票

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:45:01