然后收益率转换为列表,或直接返回列表?

时间:2018-02-03 07:20:20

标签: 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.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
...

我想知道是否已经有一个模块可以做到这一点?

1 个答案:

答案 0 :(得分:0)

The short answer is probably not, unless someone has created a module which includes the function iter2list. A "module" solution in this case won't make the task easier or more efficient.

You've already identified two good ways of exhausting a generator in a single list.

I prefer the decorator method when the generator is designed to be exhausted when used, otherwise use list(mygen()). Syntactically, I find generators more readable, so I don't usually explicitly instantiate a list and fill it.