Python iterator迭代器

时间:2022-04-26
本文章向大家介绍Python iterator迭代器,主要内容包括next() 方法、Python iterator迭代器、需要注意的地方、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

迭代器iterator是面向对象的程序设计语言都提供的遍历序列对象的一种方法,在Python中封装程度更高,其把迭代协议在语言的层面就已经实现了,所以使用起来要比其他语言方便得多。请注意,在脚本语言中(包括Python),一切数据类型都是对象。 简而言之,迭代器是遍历一组数据集中元素的一种实现方法。

迭代是一个实现可迭代对象(实现的是 iter() 方法)和迭代器(实现的是 next() 方法)的过程。可迭代对象是你可以从其获取到一个迭代器的任一对象。迭代器是那些允许你迭代可迭代对象的对象。

next() 方法

//Java迭代器示例
import java.util.*;
public class Test {
    public static void main(String[] args) {
        ArrayList arraylist = new ArrayList();
        arraylist.add("a");
        arraylist.add("b");
        arraylist.add("c");
        Iterator it = arraylist.iterator();
        while(it.hasNext()){
            String str = (String) it.next();
            System.out.println(str);
        }
    }
}
#python的next()用法 iterator是一个惰性序列

>>> list = [1, 2, 3, 4, 5]
>>> next(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
>>> it = iter(list)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

Python的iterator用法与此类似,在Python2中也有next()方法,求一组数据中的下一个元素,每调用一次next方法,指针自动后移指向下一个位置,Python中完全类似的写法为__next()__,也支持next(可迭代对象)这种写法。 当移动到最后一个元素时,如果再次调用iterator会报错(上面的Java代码中,hasNext()会做是否还有下一个元素的判断,所以不会出现错误)。

>>> list = [1, 2, 3, 4]
>>> it = iter(list)
>>> it.__next__()
1
>>>
>>> it.__next__()
2
>>> it.__next__()
3
>>> it.__next__()
4
>>> it.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Python iterator迭代器

使用iter()方法可以用可迭代对象生成一个迭代器,python的迭代器默认已经实现了next()方法,所以可以进行迭代。请注意Python3.x版本中,类似于Java的next()形式为__next()__,原因是为了规范,之后讲面向对象的时候,你会见到类似写法。

另外除了类似Java这种写法Python中也支持next(可迭代对象)这种写法,因为在Python中迭代已经进行了语言层面的封装。

>>> it = iter([1, 2, 3, 4])
>>> it.__next__()  #结果而言 等同于next(it)
1
>>> it.__next__()
2
>>> it.__next__()
3
>>> it.__next__()
4
>>> it.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

#可以使用isinstance()判断一个对象是不是迭代器
>>> from collections import Iterator
>>>
>>> isinstance((), Iterator)
False
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('', Iterator)
False
>>> isinstance(123, Iterator)
False
>>> isinstance(iter([1,2,3], Iterator))
True

需要注意的地方

生成器(generator)都是迭代器(iterator),上篇博文其实进行过说明,但反之不一定会成立。

迭代器的it.__next__()用法在遍历对象这个层面才更有意义。

事实上,Python的for循环就使用迭代器实现的。

迭代器的一个优点就是它不要求你事先准备好整个迭代过程中所有的元素。

迭代器仅仅在迭代至某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。

这个特点被称为延迟计算惰性求值(Lazy evaluation)。

Python for循环的实现机制

it = iter([1, 2, 3, 4, 5])
while True:
    try:
        i = next(it)
        print(i)
    except StopIteration:
        break
#等价于
for i in it:
    print(i)
#for循环将没有输出,因为next()已经运行到最后一个元素了
#本例证明Python的for循环中已经封装好了类似于Java迭代器的一些列操作 也是使用next()方法来进行迭代的

Python的迭代其实默认封装在了很多地方,你只要去调用就可以了,这篇博文意在说明其实现机制。

补充资料(强烈推荐): http://kuanghy.github.io/2016/05/18/python-iteration

参考资料: http://wiki.jikexueyuan.com/project/explore-python/Advanced-Features/iterator.html