yield 然后转换成一个列表,还是直接返回一个列表?

Yield then convert to a list, or returning a list directly?

我现在的代码是这样的:

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 的模块。 "module" 在这种情况下的解决方案不会使任务更容易或更有效。

您已经在一个列表中确定了两种耗尽生成器的好方法。

当生成器设计成用完即用时我更喜欢装饰器方式,否则就用list(mygen())。从句法上讲,我发现生成器更具可读性,所以我通常不会显式实例化一个列表并填充它。