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']
你期望'row2'包含什麼? DictReader()'的第一行? –
是@MartijinPieters – MAS
調用生成器函數會生成生成器對象,而不是該生成器的下一個值。創建一次發生器,將其存儲在某個地方,然後使用該發生器產生值(如在他們的答案中顯示hspandher)。 –