Python 然后转换为列表,还是直接返回列表?

Python 然后转换为列表,还是直接返回列表?,python,generator,yield,Python,Generator,Yield,我当前的代码如下: def generateRaw(self, word): for entry in self.entries: if word in html.unescape(etree.tostring(entry).decode('utf8')): yield xmltodict.parse(etree.tostring(entry)) def getRaw(self, word): return list(self.gener

我当前的代码如下:

def generateRaw(self, word):
    for entry in self.entries:
        if word in html.unescape(etree.tostring(entry).decode('utf8')):
            yield xmltodict.parse(etree.tostring(entry))

def getRaw(self, word):
    return list(self.generateRaw(word))
当然,我可以:-

def getRaw(self, word):
    result = []
    for entry in self.entries:
        if word in html.unescape(etree.tostring(entry).decode('utf8')):
            result += [xmltodict.parse(etree.tostring(entry))]
    return result
但是,什么是好的做法?什么是更好的方法

另外,最近,我发现我可以使用装饰器来转换它,但我还没有真正尝试过:-

def iter2list(func):
    def wrapped(*args):
        return list(func(*args))
    return wrapped

@iter2list
...

我想知道是否已经有了一个模块来完成这项工作?

简短的回答可能不是,除非有人创建了一个包含函数
iter2list
的模块。在这种情况下,“模块”解决方案不会使任务更容易或更高效

您已经在一个列表中找到了两种很好的发电机排气方法

当生成器被设计为在使用时耗尽时,我更喜欢decorator方法,否则使用
list(mygen())
。在语法上,我发现生成器更具可读性,所以我通常不会显式地实例化列表并填充它