只能通过csv阅读器迭代一次 [英] Can only iterate once through csv reader

查看:107
本文介绍了只能通过csv阅读器迭代一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我基本上有一个非常长的字符串列表,以及一个包含一列字符串和一列数字的CSV文件.我需要遍历非常长的字符串列表,对于每个字符串,遍历CSV文件的行,检查CSV第一列中的每个字符串,以查看它是否出现在我的字符串中,如果确实存在,则添加在另一列中的数字.最小的例子是

So I basically have an extremely long list of strings, and a CSV file that contains a column of strings and a column of numbers. I need to loop through the extremely long list of strings, and for each one, loop through the rows of the CSV file checking each string in the first column of the CSV to see if it occurs in my string, and if it does, add the number in the other column to something. A minimal sort of example would be

import csv
sList = ['a cat', 'great wall', 'mediocre wall']
vals = []
with open('file.csv', 'r') as f:
    r = csv.reader(f)
    for w in sList:
        val = 0
        for row in r:
            if row[0] in w:
                val += 1
        vals.append(val)

我可能会用到的CSV文件的示例可能是

An example of a CSV file with which I might use this could be

a, 1
great, 2

当然csv.reader(f)创建一个可迭代的对象,我只能循环一次.我在其他地方看到了使用itertools的建议,但是我发现的所有建议都是针对涉及循环访问CSV文件几次(通常只有两次)的问题.如果我尝试使用它多次遍历CSV,我不确定这将对内存消耗产生什么影响,并且总的来说,我只是想知道解决此问题的最明智的方法.

Of course csv.reader(f) creates an iterable that I can loop through only once. I've seen recommendations elsewhere to use itertools but all of the recommendations I've found have been for problems that involve looping through the CSV file a small number of times, usually just twice. If I tried to use this to loop through the CSV many times I'm unsure of what that would mean for memory consumption, and in general I'm just wondering about the smartest way to approach this problem.

推荐答案

您需要重置"文件迭代器:

You need to "reset" the file iterator:

import csv
sList = ['a cat', 'great wall', 'mediocre wall']
vals = []
with open('data.csv', 'r') as f:
    r = csv.reader(f)
    for w in sList:
        val = 0
        f.seek(0)  #<-- set the iterator to beginning of the input file
        for row in r:
            print(row)
            if row[0] in w:
                val += 1
        vals.append(val)

这篇关于只能通过csv阅读器迭代一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆