Python中的惰性评估 [英] Lazy evaluation in Python

查看:133
本文介绍了Python中的惰性评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是Python中的惰性评估?

What is lazy evaluation in Python?

一个网站说:

在Python 3.x中,range()函数返回一个特殊的范围对象,该对象按需计算列表元素(延迟或延迟评估):

In Python 3.x the range() function returns a special range object which computes elements of the list on demand (lazy or deferred evaluation):

>>> r = range(10)
>>> print(r)
range(0, 10)
>>> print(r[3])
3

这是什么意思?

推荐答案

range()(或Python2.x中的xrange())返回的对象被称为惰性迭代.

The object returned by range() (or xrange() in Python2.x) is known as a lazy iterable.

生成器没有将整个范围[0,1,2,..,9]存储在内存中,而是存储了(i=0; i<10; i+=1)的定义,并仅在需要时才计算下一个值(又称惰性求值).

Instead of storing the entire range, [0,1,2,..,9], in memory, the generator stores a definition for (i=0; i<10; i+=1) and computes the next value only when needed (AKA lazy-evaluation).

本质上,生成器使您可以返回类似于结构的列表,但这有一些区别:

Essentially, a generator allows you to return a list like structure, but here are some differences:

  1. 列表创建后将存储所有元素.生成器在需要时生成下一个元素.
  2. 列表可以根据需要进行多次迭代,生成器只能对完全进行一次迭代.
  3. 列表可以按索引获取元素,而生成器则不能-列表从头到尾只生成一次值.
  1. A list stores all elements when it is created. A generator generates the next element when it is needed.
  2. A list can be iterated over as much as you need, a generator can only be iterated over exactly once.
  3. A list can get elements by index, a generator cannot -- it only generates values once, from start to end.

可以通过两种方式创建生成器:

(1)与列表理解非常相似:

(1) Very similar to a list comprehension:

# this is a list, create all 5000000 x/2 values immediately, uses []
lis = [x/2 for x in range(5000000)]

# this is a generator, creates each x/2 value only when it is needed, uses ()
gen = (x/2 for x in range(5000000)) 

(2)作为功能,使用yield返回下一个值:

(2) As a function, using yield to return the next value:

# this is also a generator, it will run until a yield occurs, and return that result.
# on the next call it picks up where it left off and continues until a yield occurs...
def divby2(n):
    num = 0
    while num < n:
        yield num/2
        num += 1

# same as (x/2 for x in range(5000000))
print divby2(5000000)

注意:即使range(5000000)是Python3.x中的生成器,[x/2 for x in range(5000000)]仍然是列表. range(...)完成它的工作并一次生成一个x,但是创建该列表时将计算整个x/2值列表.

Note: Even though range(5000000) is a generator in Python3.x, [x/2 for x in range(5000000)] is still a list. range(...) does it's job and generates x one at a time, but the entire list of x/2 values will be computed when this list is create.

这篇关于Python中的惰性评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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