使用收益(清单)与收益 [英] Using return (list) vs yield

查看:101
本文介绍了使用收益(清单)与收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个枚举方法,一个返回一个列表,另一个返回一个yield/generator:

I've created two enumeration methods, one which returns a list and the other which returns a yield/generator:

def enum_list(sequence, start=0):
    lst = []
    num = start
    for sequence_item in sequence:
        lst.append((num, sequence_item))
        num += 1
    return lst


def enum_generator(sequence, start=0):
    num = start
    for sequence_item in sequence:
        yield (num, sequence_item)
        num += 1

对此有一些疑问:

(1)将列表更改为生成器就像执行以下操作一样简单:

(1) Is changing a list to a generator as simple as doing:

# build via list
l = list()
for item in items:
    l.append(item)

# build via iterator
# l = list() (1) <== delete this line
for item in items:
    yield item # (2) change l.append(...) to yield ...

(2)惰性评估"是使用生成器的唯一原因,还是还有其他原因?

(2) Is "lazy evaluation" the only reason to use a generator, or are there other reasons as well?

推荐答案

(1)生成器只是在向迭代中添加 yield 时创建的.

(1) generator are simply created as adding yield to your iteration.

(2)是,用于延迟评估.但是生成器也可用于创建堆栈和队列,因为它们只能迭代一次.通过产生上下文,在上下文管理器中也可以利用此属性.

(2) Yes, for lazy evaluation. But generators are also used to create stack and queue as they can be only iterate once. This property is also exploited in context manager, by yielding the context.

这篇关于使用收益(清单)与收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆