为什么这两个相同的函数会创建两个输出进程?

2024-04-19 18:35:55 发布

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

我试图检查我的函数的有效性,我注意到我的两个具有相同代码的函数给出了两个不同的输出。我需要更改其中一个的if条件,但我也需要确保它们都正常工作。可以

data_out = open("mentees_all_attributes.csv", "rU")
reader = csv.reader(data_out)
next(reader,None)


def primaryWithParticipatedCounts(jobs, count):
    for line in reader:  
        cells = line
        new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[
            10]  # name, # of participation, primary occupation/industry, secondary occupation/industry
        if int(new_cell[1]) > 0:  # Isolate all the participants with more than 0
            primary = new_cell[2]
            if primary == jobs:
                count += 1

    return jobs, count

print primaryWithParticipatedCounts(A012,a012counts)


def primaryWithoutParticipatedCounts(jobs, count):
    for line in reader:  
        cells = line
        new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[
            10]  
        if int(new_cell[1]) > 0:  
            primary = new_cell[2]
            if primary == jobs:
                count += 1

    return jobs, count

print primaryWithoutParticipatedCounts(A012,a012counts)

返回输出为:

('[A012]', 3)
('[A012]', 0)

Tags: csv函数newdataifcountlinejobs
2条回答
data_out.seek(0) between the funcs

你的两个功能似乎是一样的(除非我忽略了什么)。问题似乎出在reader。读取器和任何文件句柄一样,是一个iterator,一旦您迭代了读取器中的所有行,它就被耗尽了。因此,当您对第二个函数再次使用相同的reader时,没有更多的行可读取,并且count最终成为0

您可以尝试以下任一操作:

  • 打开文件并函数中,而不是重复使用同一读取器两次
  • 把这些行读入一个列表:lines = list(reader);只适用于小文件
  • 在再次使用读卡器之前,请将文件句柄倒带到开头:data_out.seek(0)

相关问题 更多 >