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

时间:2019-06-22 12:43:49

标签: python iterator generator

我是编程新手,并且在概念上遇到麻烦。

在课堂上有人说,使用生成器来分解执行。其次,也有人说:“使用生成器时,我们会执行惰性评估,从而产生隐式可迭代序列。”

我不理解为什么它是“惰性评估”的概念。具有隐式可迭代序列意味着什么?那不是迭代器的作用吗?

大多数在线网站都谈到了迭代器和生成器之间的区别,但是我不明白中断执行可能意味着什么。由于我们只能在执行过程中使用生成器。这是否意味着它像return语句一样工作?

1 个答案:

答案 0 :(得分:0)

看看下面的生成器示例:

# 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]