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

Python字典语法求助:CSV选举数据的候选人票数存储与展示

问题说明

第一次用Python字典处理CSV格式的选举数据,想把候选人姓名和对应票数存入字典,最终输出如下格式的结果:

Election Results
-------------------------
Total Votes: 369711
-------------------------
Charles Casper Stockham: 23.049% (85213)
Diana DeGette: 73.812% (272892)
Raymon Anthony Doane: 3.139% (11606)

目前已经能统计出各候选人的票数,但字典用法不对,原代码如下:

# Import the os module
import os

# Module for reading CSV files
import csv

# Store the file path associated with the file
csvpath = os.path.join('Resources', 'election_data.csv')

# Open the file "read mode" and store contents in the variable
with open(csvpath) as csvfile:

    csvreader = csv.reader(csvfile, delimiter =',')

    print(csvreader)

    csv_header = next(csvreader)

    total_ballots = 0 
    sumCharles = sumDiana = sumRaymon = 0
    candidates = dict()
    candidates_list = ["Charles Casper Stockham","Diana DeGette","Raymon Anthony Doane"]
    candidates["names"] = candidates_list
    votes_list = [sumCharles , sumDiana , sumRaymon]
    candidates["votes"] = votes_list

    for row in csvreader:
        total_ballots = total_ballots + 1
        if (row[2] == "Charles Casper Stockham"):
            sumCharles = sumCharles + 1
        if (row[2] == "Diana DeGette"):
            sumDiana = sumDiana + 1
        if (row[2] == "Raymon Anthony Doane"):
            sumRaymon = sumRaymon + 1
    
    print(candidates)
    print(total_ballots)
优化后的代码及说明

你现在的字典结构把姓名和票数拆成两个列表,后续处理很麻烦。正确的做法是用候选人姓名作为字典的键,票数作为对应的值,操作起来直接高效。优化后的代码如下:

import os
import csv

csvpath = os.path.join('Resources', 'election_data.csv')

with open(csvpath) as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    next(csvreader)  # 跳过表头
    
    total_ballots = 0
    candidate_votes = {}  # 键:候选人姓名,值:票数

    for row in csvreader:
        total_ballots += 1
        candidate = row[2]
        # 如果候选人已在字典中,票数+1;否则初始化票数为1
        if candidate in candidate_votes:
            candidate_votes[candidate] += 1
        else:
            candidate_votes[candidate] = 1

    # 输出结果
    print("Election Results")
    print("-------------------------")
    print(f"Total Votes: {total_ballots}")
    print("-------------------------")
    # 遍历字典计算百分比并输出
    for name, votes in candidate_votes.items():
        percentage = (votes / total_ballots) * 100
        # 格式化百分比为三位小数
        print(f"{name}: {percentage:.3f}% ({votes})")

关键改进点:

  1. 字典结构优化:直接用{候选人: 票数}的键值对存储,无需单独维护姓名列表和票数列表,逻辑更清晰
  2. 兼容性更强:就算CSV里出现新的候选人,代码也能自动统计,不用提前手动添加候选人名称
  3. 输出逻辑简化:遍历字典的键值对就能直接计算百分比并按要求格式输出,不用再对应索引找数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:54:22