python迭代器的实例详解


本文摘自php中文网,作者零下一度,侵删。

可直接作用于for循环的对象叫做可迭代对象(iterable);

可被next()函数调用并不断返回下一个值的对象称为迭代器(iterator);

所有的可迭代对象均可以通过内置函数iter()来转变为迭代器。

在使用for循环的时候,程序就会自动调用即将处理的对象的迭代器对象,然后使用它的next()方法,直到检测一个stoplteration异常。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

>>> l = [4,5,6,7,8,9,0]   #这是一个列表

>>> i = iter(l)                 #可迭代对象转换为迭代器;

>>> next(i)

4

>>> next(i)

5

>>> next(i)

6

>>> next(i)

7

>>> next(i)

8

>>> next(i)

9

>>> next(i)

0

>>> next(i)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration

因为列表中么有超过0的数字,所以当范围超过的话,就会返回一个StopIteration异常。

在生产环境中如何判断呢

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

>>> L = [4,5,6]

>>> I = L.__iter__()

>>> L.__next__()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: 'list' object has no attribute '__next__'

>>> I.__next__()

4

>>> from collections import Iterator, Iterable

>>> isinstance(L, Iterable)

True

>>> isinstance(L, Iterator)

False

>>> isinstance(I, Iterable)

True

>>> isinstance(I, Iterator)

True

>>> [x**2 for x in I]   

[25, 36]

以上就是python迭代器的实例详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

如何用Python画三角形

如何利用Python将byte array转为string

Python中yield什么意思

Python定制类__str__(实例详解)

Python变量类型-Python字符串str()的用法(示例)

Python分数怎么表示什么

Python安装完后怎么用

Python中闭包的简单介绍(附示例)

Python闰年判定代码是什么

如何用Python计算基本统计值?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...