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
·
回答问题
我写了一个应该返回字典的生成函数。但是,当我尝试打印字段时,出现以下错误
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']
Answers
生成器返回一个迭代器,你需要明确地调用 next 。
你的最后一行代码应该是这样的 -
rows_generator = genSearch(SearchInfo)
row2 = next(rows_generator, None)
print row2['SearchDate']
理想情况下,我们在循环中使用迭代器,它会自动为我们做同样的事情。
更多推荐
已为社区贡献126483条内容
所有评论(0)