【问题标题】:What does it mean that as compared to iterator, generators gives back an implicit iterable sequence?与迭代器相比,生成器返回一个隐式的可迭代序列是什么意思?
【发布时间】:2019-06-22 12:43:49
【问题描述】:

我是编程新手,遇到了一个概念性问题。

在课堂上说过,生成器用于分解执行。其次,也有人说“当使用生成器时,我们执行惰性求值,这会产生一个隐式的可迭代序列。”

我不明白为什么它是“惰性评估”的概念。隐含的可迭代序列意味着什么?这不就是迭代器的用途吗?

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

【问题讨论】:

    标签: python iterator generator


    【解决方案1】:

    看看下面的生成器示例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2018-08-16
      • 2018-05-24
      相关资源
      最近更新 更多