为什么函数要接受所有的值?

2024-09-27 21:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现一个问题。。。当我执行第一个函数时,它会从我导入的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 [ ]

Tags: 文件csvthe函数inwithfile1are
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:28

csv.reader()遵循iterator协议。由于您在两个函数之间共享同一个reader对象,因此reader在进入第二个函数之前已经到达了迭代的末尾。当第二个函数通过调用读取器上的next()获取记录时,它位于列表的末尾

您可以尝试以下方法之一:

  1. 将文件路径传递给这两个函数
import csv


def total_votes(election_data_file):
    with open(election_data_file) as file1:
        reader1 = csv.reader(file1)
        f1 = [vote1[0] for vote1 in reader1]
        print(f"The total number of voters are: {len(f1) - 1}")


def unique_candidates(election_data_file):
    b = []
    with open(election_data_file) as file1:
        reader1 = csv.reader(file1)
        for cd1 in reader1:
            if cd1[2] == "Candidate":
                None
            elif cd1[2] not in b:
                b.append(cd1[2])
    return f"\nThe candidates taking part in elections are {b}"


election_data_file = 'election_data_1-2.csv'
total_votes(election_data_file)
unique_candidates(election_data_file)

  1. 将文件数据加载到内存中并将其传递给函数(如果文件太大而无法放入内存,则会出现问题。)
import csv


def total_votes(election_data):
    f1 = [vote1[0] for vote1 in election_data]
    print(f"The total number of voters are: {len(f1) - 1}")


def unique_candidates(election_data):
    b = []
    for cd1 in election_data:
        if cd1[2] == "Candidate":
            None
        elif cd1[2] not in b:
            b.append(cd1[2])
    return f"\nThe candidates taking part in elections are {b}"


election_data = []
with open('election_data_1-2.csv') as file1:
    reader1 = csv.reader(file1)
    election_data = list(reader1)

total_votes(election_data)
unique_candidates(election_data)

相关问题 更多 >

    热门问题