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

Python中如何逐个遍历JSON数组列按轮次统计候选人得票数

实现方案

核心逻辑

  • 先统计所有投票的最长偏好选择长度,作为总计票轮次
  • 逐轮遍历,仅统计当前顺位的有效投票(投票者填写了当前顺位选择才计入)
  • 每轮统计完成后输出对应轮次的得票结果

完整实现代码(main.py)

import json

with open('data.json', 'r') as f:
    db = json.load(f)

# 存储候选人基础信息
candidates_base = {}
for candidate in db["candidates"]:
    candidates_base[candidate["id"]] = candidate["name"]

# 计算总计票轮次(由最长的投票偏好数组决定)
max_round = max(len(vote) for vote in db["votes"])

# 逐轮统计得票
for round_idx in range(max_round):
    current_round = round_idx + 1
    # 初始化当前轮得票
    round_votes = {cid: 0 for cid in candidates_base.keys()}
    # 遍历所有投票统计当前顺位
    for vote in db["votes"]:
        if len(vote) > round_idx:
            selected_cid = vote[round_idx]
            round_votes[selected_cid] += 1
    # 打印当前轮结果
    print(f"=== 第{current_round}轮计票结果 ===")
    for cid, cnt in round_votes.items():
        print(f"候选人{candidates_base[cid]}得票数:{cnt}")
    print()

运行结果(基于示例data.json)

=== 第1轮计票结果 ===
候选人Stan得票数:2
候选人Avia得票数:2
候选人Bob得票数:2

=== 第2轮计票结果 ===
候选人Stan得票数:2
候选人Avia得票数:2
候选人Bob得票数:1

=== 第3轮计票结果 ===
候选人Stan得票数:1
候选人Avia得票数:0
候选人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.03 20:09:02