python中iterable和iterator的联系和区别

python中iterableiterator的联系和区别:

国外某论坛的解释:
Iterable is an object, which one can iterate over. It generates an Iterator when passed to iter() method.

Iterator is an object, which is used to iterate over an iterable object using __next__() method. Iterators have __next__() method, which returns the next item of the object.

Note that every iterator is also an iterable, but not every iterable is an iterator. For example, a list is iterable but a list is not an iterator. An iterator can be created from an iterable by using the function iter() . To make this possible, the class of an object needs either a method __iter__, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.

翻译成中文并进行补充:
Iterable是一个可以迭代的对象。其定义了__iter()__ 方法,用以生成Iterator;同时iterable对象还定义了一个__getitem__()方法,该方法可以从零开始执行顺序索引(并在索引不再有效时引发IndexError)。

Iterator也是一个对象,其定义了__next__ ()方法,用来迭代可迭代对象,该方法返回被迭代对象的下一个item。

所有iterator都是iterable,但并非所有iterable都是iterator。 例如,列表(list) 是iterable,但不是iterator。 可以使用函数 iter() 将一个iterable转变为一个iterator

例子:
平时我们所使用的 for i in [1,2,3],实际上是对iterable[1,2,3]使用了__iter__() 方法,将其变成了一个iterator,再使用__next__方法对其进行遍历。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值