从循环中返回元素,一次一个

时间:2014-08-26 19:40:06

标签: python dictionary

我有一个简单的函数来解析.csv如下

def grabber3(datafile):

with open(datafile, 'rb') as f:
    r =csv.DictReader(f)
    for line in r:
        del line['thisthing']
        print line

这样可以正确打印每条dict行,大约50行,如

{'NetworkStatus': '1', 'ID': '1469'}
{'NetworkStatus': '1', 'ID': '1470'}
etc etc

但是我想在调用函数时返回这个,所以我将print语句更改为

def grabber3(datafile):

with open(datafile, 'rb') as f:
    r =csv.DictReader(f)
    for line in r:
        del line['thisthing']
    return line

但它只返回第一行

{'NetworkStatus': '1', 'ID': '1469'}

如何返回循环/所有dict行的每一行而不是第一行?

1 个答案:

答案 0 :(得分:7)

这样做的有效方法是使用yield

def grabber3(datafile):
    with open(datafile, 'rb') as f:
        r =csv.DictReader(f)
        for line in r:
            del line['thisthing']
            yield line

然后在调用此函数的代码中,您可以执行以下操作:

dict_generator = grabber3(a_file)

然后迭代这个dict_generator

for a_dict in dict_generator:
    print a_dict

有关yield和生成器的更多内容:

  1. https://wiki.python.org/moin/Generators
  2. What does the "yield" keyword do in Python?