python3:iterable(可迭代对象) vs iterator(可迭代对象)

一.iterator(迭代器)

 官方文档定义:

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__()method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter()function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

More information can be found in Iterator Types.

翻译:

iterator是一个表示数据流的对象。重复调用迭代器的__next__()方法(或将迭代器传递给内置函数next())将返回数据流中的连续项。当没有数据可访问时,将会引发一个StopIteration异常。这个时候,迭代器对象已耗尽,后续任何对__next__()方法的进一步调用都将会再次引发StopIteration异常。

迭代器需要有一个__iter__()方法,__iter__()方法返回迭代器对象本身,所以任何一个迭代器都是可迭代对象,并且可以在在大部分接受可迭代对象的地方使用。一个值得注意的列外是尝试多次迭代传递的代码。

当一个容器对象(如list)被传递给iter()方法的时候或者在for循环中使用的时候,都会生成一个新的迭代器对象— —使用迭代器尝试这样的操作只会返回上一次迭代过程中使用的相同的耗尽的迭代器对象,这样使迭代器起来像一个空容器。

解释:

# -*- coding:utf-8 -*-
from collections.abc import Iterator


'''
 迭代器本质:支持迭代器协议,即实现 __iter__() 与 __next__() 两个方法
 __next__():(在Python 2 里是 next())执行两个操作:
              1.更新iterator状态,使其指向下一项,以便下一次调用。
              2.返回当前结果。
              没有数据可访问时,引发StopIteration异常
 __iter__():返回迭代器对象本身
'''


class MyNumbers:
    def __init__(self, n):
        self.index = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.index <= self.n:
            i = self.index
            self.index += 1
            return i
        else:
            raise StopIteration


my_iterator = MyNumbers(3)
print(next(my_iterator))  # 0
print([i for i in my_iterator])  # [1, 2, 3]
print([i for i in my_iterator])  # []

二.iterable(可迭代对象)

官方文档定义:

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as liststr, and tuple) and some non-sequence types like dictfile objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements Sequence semantics.

Iterables can be used in a for loop and in many other places where a sequence is needed (zip()map(), …). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iteratorsequence, and generator.

翻译:

iterable是一个能够一次返回其一个成员的对象。可迭代对象包括所有的序列类型(如list, str, tuple)、一些非序列数据类型(如dict, file objects )、所有定义了__iter__()方法的类对象、所有定义了实现序列语义的__getitem__()方法的类对象。

可迭代对象可以在for循环中使用以及其他许多需要序列的地方(zip(), map(), ...)。当可迭代对象作为参数被传递给内建函数iter()调用时,iter()返回一个迭代器对象。迭代器适用于一组值的一次传递。当使用可迭代对象时,通常不需要自己调用iter()方法或者处理迭代器对象,因为for 语句会自动为你执行该操作——它会在循环期间为你创建一个临时的未命名变量来保存迭代器。参考:iteratorsequence, 和 generator

解释:

# -*- coding:utf-8 -*-
from collections.abc import Iterable, Iterator


# 可迭代对象是可作用for循环的对象,一次只返回一个值
lst = [1, 2, 3, 4, 5, 6]
for i in lst:
    print(i, end=' ')  # 1 2 3 4 5 6

# 判断是否是可迭代对象:isinstance
print(isinstance(lst, Iterable))  # True

# iter()方法可以把可迭代对象转为迭代器
change_lst = iter(lst)
change_lst2 = lst.__iter__()
print(type(change_lst))  # <class 'list_iterator'>
print(type(change_lst2))  # <class 'list_iterator'>

三.参考资料

[1]Python之生成器详解:http://kissg.me/2016/04/09/python-generator-yield/#generator

猜你喜欢

转载自blog.csdn.net/cckavin/article/details/86342918