与迭代器相比,生成器返回隐式可迭代序列是什么意思?



我是编程新手,正面临一个概念问题的麻烦。

课堂上有人说,生成器用于分解执行。其次,也有人说"当使用生成器时,我们执行惰性求值,从而产生隐式可迭代序列。

我不明白为什么它是"懒惰评估"的概念。拥有隐式可迭代序列意味着什么?这不是迭代器的用途吗?

大多数在线网站只是谈到迭代器和生成器之间的区别,但我不明白分解执行可能意味着什么。因为我们只能在执行过程中使用生成器。这是否意味着它的工作方式类似于返回语句?

看看下面的生成器示例:

# Lazy evaluation. Instead of an "instant" complete result
# you get an iterator that you can execute in steps to get
# all results, one by one.
# This can be useful to save memory if the results are big,
# or to advance code execution in steps, because the generator
# remembers state between next() calls
def get_three_ints(start=0):
    for next_int in range(start, start+3):
        print("I'm running!") # advance a little more in code
        yield next_int # suspend execution here. Wait for
                       # another next() # while returning
                       # next_int

gen = get_three_ints(5) # gen is a generator function because of yield
print(next(gen))
print(next(gen))
print(next(gen))
try:
    print(next(gen)) # raises StopIteration (the iterator was consumed)
except StopIteration:
    print("Got a StopIteration.n")
# Another generator. A generator is implicitely iterable.
gen = get_three_ints(10)
for i in gen:
    print(i)
# This is because both an __iter__ and __next__ special methods
# were created in your generator object just by using the keyword yield
print()
print(type(gen),'n')
gen_attrs = dir(gen)
print('__iter__' in gen_attrs)
print('__next__' in gen_attrs)
# The "opposite" of this is creating a function that executes at once
# and returns the complete result
def get_three_ints_now(start=0):
    return list(range(start, start+3))
print()
print(get_three_ints_now(20))
# Output:
I'm running!
5
I'm running!
6
I'm running!
7
Got a StopIteration.
I'm running!
10
I'm running!
11
I'm running!
12
<class 'generator'> 
True
True
[20, 21, 22]

最新更新