如何编写Python函数读取CSV文件并返回一维投票计数列表
实现CSV投票数据提取函数
下面提供两种实现方案,分别基于标准库csv和pandas库,都能按指定候选人顺序,将CSV中每行的投票数整合为一维列表返回。
方案一:使用标准库csv
无需额外依赖,适合轻量场景:
import csv def retrieveData(filename, nominees): result = [] # 用with语句自动管理文件,避免资源泄漏 with open(filename, 'r') as file: csv_reader = csv.reader(file) # 获取CSV表头,建立候选人与列索引的对应关系 header = next(csv_reader) nominee_col_indices = [header.index(nominee) for nominee in nominees] # 遍历每一行数据,按顺序提取投票数 for row in csv_reader: # 将投票字符串转为整数,收集当前行的投票数据 row_votes = [int(row[idx]) for idx in nominee_col_indices] # 把当前行的投票数追加到结果列表(展开为一维) result.extend(row_votes) return result nominees = ["Obama","Romney","Johnson","Stein","Others"] # 调用函数并打印结果 print(retrieveData("ElectionUSA2012.csv", nominees))
方案二:使用pandas库
代码更简洁,处理大文件效率更高:
import pandas as pd def retrieveData(filename, nominees): # 读取CSV文件为DataFrame vote_df = pd.read_csv(filename) # 按指定候选人顺序选择列,将二维数据展平为一维列表 result = vote_df[nominees].values.flatten().tolist() return result nominees = ["Obama","Romney","Johnson","Stein","Others"] # 调用函数并打印结果 print(retrieveData("ElectionUSA2012.csv", nominees))
注意事项
- 确保CSV文件的表头包含
nominees列表中的所有候选人名称,否则会抛出索引异常 - 如果CSV中的投票数带有千位分隔符(如
1,234),需要先清洗字符串再转换为数值
内容的提问来源于stack exchange,提问作者ibra
相关产品推荐
相关产品推荐

