Python 类型错误:“生成器”对象没有属性“__getitem__”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30844089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:04:17  来源:igfitidea点击:

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

pythonpython-2.7dictionaryyieldyield-return

提问by MAS

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

采纳答案by hspandher

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

Generator 返回一个迭代器,你需要明确地调用 next 。

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.

理想情况下,我们在循环中使用迭代器,它会自动为我们做同样的事情。

回答by Reza Saidafkan

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

生成器必然是迭代器,而不是迭代器。迭代器包含 __item__()__getitem__()方法,而迭代器包含next()/__next__()方法(python 版本 2.x/3.x)。