我发现一个问题。。。当我执行第一个函数时,它会从我导入的csv文件中取出数据并使用它,这就是为什么没有任何东西留给其他函数执行。。。如何纠正? 如果第二个函数是单独执行的,它会给出所需的结果
CSV文件有3行,即选民id号、县、候选人
import csv
with open('election_data_1-2.csv') as file1:
reader1 = csv.reader(file1)
def total_votes():
f1 = [vote1[0] for vote1 in reader1]
print("The total number of voters are:",len(f1)-1)
def unique_candidates():
b = []
for cd1 in reader1:
if cd1[2] == "Candidate"
None
elif cd1[2] not in b:
b.append(cd1[2])
return ("\nThe candidates taking part in elections are",b)
total_votes()
unique_candidates()
--------------------------------------------------------------------------------
Result with the second function:
The candidates taking part in elections are ['Vestal','Torres','Seth','Khan']
Result with both the functions:
The total number of voters are: 4324001
The candidates taking part in elections are [ ]
csv.reader()遵循iterator协议。由于您在两个函数之间共享同一个reader对象,因此reader在进入第二个函数之前已经到达了迭代的末尾。当第二个函数通过调用读取器上的
next()
获取记录时,它位于列表的末尾您可以尝试以下方法之一:
相关问题 更多 >
编程相关推荐