TypeError: 'generator' object has no attribute '__getitem__'

谁说我不能喝 提交于 2019-12-06 19:12:33

问题


I have written a generating function that should return a dictionary. however when I try to print a field I get the following error

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

This is my code

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

回答1:


Generator returns an iterator, you explicitly needs to call next on it.

Your last line of code should be something like -

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

Ideally, we use iterators in a loop, which automatically does the same for us.




回答2:


Generators are necessarily iterators , not iterables. Iterables contain __item__() and __getitem__() methods, whilst iterators contain next() / __next__() method (python version 2.x/3.x).



来源:https://stackoverflow.com/questions/30844089/typeerror-generator-object-has-no-attribute-getitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!