TypeError:'generator'对象没有属性'__getitem__'

时间:2015-06-15 11:32:42

标签: python python-2.7 dictionary yield yield-return

我编写了一个应该返回字典的生成函数。但是当我尝试打印字段时,我收到以下错误

print row2['SearchDate']
TypeError: 'generator' object has no attribute '__getitem__'

这是我的代码

from csv import DictReader
import pandas as pd
import numpy as np


def genSearch(SearchInfo):
    for row2 in DictReader(open(SearchInfo)):
        yield row2

train = 'minitrain.csv'

SearchInfo = 'SearchInfo.csv'

row2 = {'SearchID': -1}

for row1 in DictReader(open(train)):
    if 'SearchID' in row1 and 'SearchID' in row2 and row1['SearchID'] == row2['SearchID']:
        x = deepcopy( row1 )
        #x['SearchDate'] = row2['percent']
        x.update(row2)    
        print 'new'
        print x
    else: 
        #call your generator
        row2 = genSearch(SearchInfo)
        print row2['SearchDate']

2 个答案:

答案 0 :(得分:9)

Generator返回一个迭代器,你明确需要在它上面调用它。

你的最后一行代码应该是 -

rows_generator = genSearch(SearchInfo)
row2 = next(rows_generator, None)
print row2['SearchDate']

理想情况下,我们在循环中使用迭代器,它会自动为我们做同样的事情。

答案 1 :(得分:6)

生成器必须是迭代器,而不是 iterables 。 Iterables包含  __item__()__getitem__()方法,而迭代器包含next() / __next__()方法(python版本2.x / 3.x)。