【问题标题】:How do I loop through a csv file and create a list based on the values in the list?如何遍历 csv 文件并根据列表中的值创建列表?
【发布时间】:2021-04-09 00:06:22
【问题描述】:

我有一个包含三列(ID、县和候选人)的 csv 文件。有四个候选人,我需要创建四个列表(每个候选人一个)。每次候选人的名字出现在列表/列中时,我都想将该名字添加到新列表中,然后获取最后一个列表的长度,以查看他们获得了多少票。当我运行脚本时,它成功打印了总票数,但是每个候选人列表的长度都打印为“0”,所以我认为他们没有成功添加到列表中。

我对 python 还很陌生。我相信我的错误在于我的循环方式和 if 语句。

谢谢。

with open(poll_path, 'r') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')

#skip the header
    next(csvreader,None)

python/
    votes = 0
    votes = []
    candidate_list = 0
    candidate_list = []
    khan = 'Khan'
    khan = []
    kahn = 0
    correy = "Correy"
    correy = []
    correy = 0
    li = "Li"
    li = []
    li = 0
    otooley = "O'Tooley"
    otooley = []
    otooley = 0
    for row in csvreader:
        votes_cast=str(row[0])
        votes.append(votes_cast)
        candidates=str(row[2])
        candidate_list.append(candidates)
        if row[2] == str(khan):
            khan.append(candidate_list)
            
        if row[2] == str(correy):
            correy.append(candidate_list)
            
        if row[2] == str(li):
            li.append(candidate_list)

        if row[2] == str(otooley):
            otooley.append(candidate_list)
            
    total_votes = len(votes)
    print("Election Results")
    print("----------------------------")
    print("Total Votes: " + str(total_votes))
    print("----------------------------")
    kahn_votes = len(khan)
    print(kahn_votes)
    correy_votes = len(correy)
    print(correy_votes)
    li_votes = len(li)
    print(li_votes)
    otooley_votes = len(otooley)
    print(otooley_votes)

【问题讨论】:

  • 如果您在脚本之前/之后显示数据的样子以及您想要的结果,您的帖子会更清晰
  • 这是我得到的结果。 (PythonData) C:\Users\hilar\python_challenge\PyPoll\Resources>python testing.py 选举结果 ----------------------------总票数:3521001 ---------------------------- 0 0 0 0

标签: python list csv conditional-statements


【解决方案1】:

您的代码有很多问题。当您多次分配变量时,如

khan = 'Khan'
khan = []
kahn = 0

您不断丢失早期的值。 kahn0 并且字符串和列表都消失了。前两行毫无意义。

votes_cast=str(row[0])

csv 模块只创建字符串,不需要str 一个字符串。

if row[2] == str(khan):

你知道khan0 吗?是的,这只是将第 2 行与字符串“0”进行比较,所以我失败了。因为khan 一开始就应该是字符串,所以你也不应该强制转换它。

有一种更好的方法可以使用字典来跟踪候选计数。代码的一般说明

  • 使用字典跟踪候选计数
  • 不要明确使用默认值。 open("foo", "r") should be open("foo")
  • 不要硬编码候选,只使用文件中的内容
  • 将 csv 行解压缩到变量中以提高可读性

代码

import csv

candidate_count = {}

with open(poll_path, newline=None) as csvfile:
    csvreader = csv.reader(csvfile)
    for ID, county, candidate in csvreader:
        if candidate not in candidate_count:
            candidate_count[candidate] = 0
        candidate_count[candidate] += 1

# we can sort by total counts to print
for candidate, votes in sorted(candidate_count.items(), key=lambda kv: kv[1]):
    print(candidate, votes)

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2021-01-20
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多