2015-06-15 105 views
4

我寫了一個應該返回字典的生成函數。然而,當我嘗試打印領域,我得到以下錯誤TypeError:'generator'對象沒有屬性'__getitem__'

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

你期望'row2'包含什麼? DictReader()'的第一行? –

+0

是@MartijinPieters – MAS

+1

調用生成器函數會生成生成器對象,而不是該生成器的下一個值。創建一次發生器,將其存儲在某個地方,然後使用該發生器產生值(如在他們的答案中顯示hspandher)。 –

回答

4

發電機返回一個迭代器,你需要明確未來調用就可以了。

你的代碼最後一行應該是這樣的 -

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

發電機必然迭代,不iterables。可計算元件包含 __item__()__getitem__()方法,而迭代器包含next()/__next__()方法(Python版本2.x/3.x)。

相關問題