简体   繁体   English

Python3迭代器与生成器

[英]Python3 Iterators vs generators

I have a program below that I tried to understand the difference between an iterator and a generator.I get that a generator is an iterator and more . 我下面有一个程序,我试图理解迭代器和生成器之间的区别。我知道生成器是一个迭代器more I appreciate the generators are short and succinct way to generate iterators. 我感谢生成器是生成迭代器的简短方法。 But other than brevity is there some other feature that generators provide that iterators doesn't 但是除了简洁之外,生成器还提供了其他一些功能,迭代器没有

def squares(start, stop):
    for i in range(start, stop):
        yield i * i

generator = squares(1, 10)

print(list(generator))


class Squares(object):
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.start >= self.stop:
            raise StopIteration
        current = self.start * self.start
        self.start += 1
        return current


iterator = Squares(1, 10)

l = [next(iterator) for _ in range(1,10)]
print(l)

The two examples that you've posted are equivalent. 您发布的两个示例是等效的。

The main advantages that generators offer over iterators (that aren't generators) is that generators use less memory, can be faster, and can be used on infinite streams. 生成器相对于迭代器(不是生成器)提供的主要优点是生成器使用更少的内存,可以更快,可以在无限流上使用。

When you use an iterator, all the items that are going to be returned eventually are calculated, then the first the element is returned. 使用迭代器时,将最终计算将要返回的所有项目,然后首先返回元素。

With a generator the first element is returned before the second item is calculated. 使用生成器时,在计算第二项之前返回第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM