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

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']

最佳答案

Generator返回一个迭代器,您明确需要在其上调用next。

您的最后一行代码应类似于-

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

理想情况下,我们在循环中使用迭代器,它会自动为我们执行相同的操作。

关于python - TypeError : 'generator' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30844089/

10-13 05:04