python - 类型错误 : 'generator' object has no attribute '__getitem__'

标签 python python-2.7 dictionary yield yield-return

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

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 - 类型错误 : 'generator' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844089/

相关文章:

python - 将元组和 int 键字典写入文件

python - 最快的获取方式

linux - EC2 实例 : Cannot allocate memory

python - 如何从 Python 中的字典中获取所需的值

arrays - Swift:将字符串中的单独字符与字典中的值匹配

python - 在 Python 中高效创建(播种)大型字典

android - 命令失败 : tar xzf android-sdk_r20-linux. tgz

python - 尝试调整由matplotlib.pyplot打印出的图像的大小

python - "ImportError: No module named httplib2"即使在安装后

python - django- celery : TypeError: can only concatenate tuple (not "NoneType") to tuple