在Python中,什么是懒惰?
一个网站说:
在Python 3中.x range()
函数返回一个特殊的范围对象,该对象按需计算列表中的元素(延迟或延迟求值):
>>> r = range(10)
>>> print(r)
range(0, 10)
>>> print(r[3])
3
这是什么意思?
在Python中,什么是懒惰?
一个网站说:
在Python 3中.x range()
函数返回一个特殊的范围对象,该对象按需计算列表中的元素(延迟或延迟求值):
>>> r = range(10)
>>> print(r)
range(0, 10)
>>> print(r[3])
3
这是什么意思?
range()
(或Python2.x中的xrange()
)返回的对象称为lazy iterable.
生成器没有将整个范围[0,1,2,..,9]
存储在内存中,而是存储(i=0; i<10; i+=1)
的定义,并仅在需要时计算下一个值(也称为惰性计算).
本质上,生成器允许您返回类似列表的 struct ,但这里有一些区别:
A generator can be created in two ways:
(1) 与列表理解非常相似:
# 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
返回下一个值:
# 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)
Note:尽管range(5000000)
在Python3中是一个发生器.x、 [x/2 for x in range(5000000)]
仍然是一个列表.range(...)
执行它的任务,一次生成x
个值,但创建此列表时,将计算x/2
个值的整个列表.