[Python基础知识]
来源:互联网 发布:js原型链是啥 编辑:程序博客网 时间:2024/06/15 05:36
在Python学习中我们经常看到这三个词,但是总是无法精准的定义它们的含义,以下是我从网上和文档中总结的定义:
iteration
iteration(迭代) 是在一行元素中一次取一个元素的过程
iterator
iterator 是一个可迭代对象,它具有 next() (Python2)或 __next__() (Python3)方法。
在Python3中,当没有更多的元素时,__next __() 引发一个StopIteration异常,它告诉for循环终止。
>>> s = 'abc'>>> it = iter(s)>>> it<iterator object at 0x00A1DB50>>>> next(it)'a'>>> next(it)'b'>>> next(it)'c'>>> next(it)Traceback (most recent call last): File "<stdin>", line 1, in <module> next(it)StopIteration
iterable
iterable 是一个迭代器对象,它具有 __iter__() 方法并返回一个iterator ,或具有__getitem__()方法并可以从零开始的顺序索引(并且当索引不再有效时引发IndexError)。
Python里有大量内置的 iterable 类型,如 str、list、tuple、dict、file、range等
In [1]: s = 'abc'In [2]: s.__iter__()Out[2]: <str_iterator at 0x2200bc10f28>In [3]: l = ['a', 'b', 'c']In [4]: l.__iter__()Out[4]: <list_iterator at 0x2200bc101d0>In [5]: t = ('a', 'b', 'c')In [6]: t.__iter__()Out[6]: <tuple_iterator at 0x2200bbd0710>In [7]: d = {'a':1, 'b':2, 'c':3}In [8]: d.__iter__()Out[8]: <dict_keyiterator at 0x2200bb1d0e8>...
举例
看到了迭代器协议背后的机制,很容易将迭代器行为添加到类中。定义一个 __iter__()方法返回对象的__next__() 方法。如果类定义了__next__(),那么__iter__()可以仅仅返回self:
class Reverse: """迭代器逆序循环一个序列。""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index]
>>> rev = Reverse('spam')>>> iter(rev)<__main__.Reverse object at 0x00A1DB50>>>> for char in rev:... print(char)...maps
附录
参考资料:
iterators section of the tutorial:
https://docs.python.org/3/tutorial/classes.html#iterators
iterator types section of the standard types page
https://docs.python.org/dev/library/stdtypes.html#iterator-types
iterators section of the Functional Programming HOWTO
https://docs.python.org/dev/howto/functional.html#iterators
- python基础知识
- Python 基础知识
- Python 基础知识
- python基础知识
- python基础知识
- python基础知识
- python基础知识
- Python基础知识
- python基础知识
- python基础知识
- Python-基础知识
- python基础知识
- python基础知识
- Python基础知识
- python基础知识
- python基础知识
- python基础知识
- Python:基础知识
- 关于Python3.5将.py文件打包为.exe文件
- Linux上Mysql数据库安装
- 如何在ceph中找出存放的数据
- 微信开发-坑爹的80端口映射之nginx
- 图像处理之边界跟踪
- [Python基础知识]
- 5.10正确版
- 【云星数据---mesos实战系列003】:marathon实战004--marathon部署一套Tomcat环境(精简代码版)
- 负数的二进制表示
- 关于解决maven中 unable to compile jsp 问题
- 组合模型——Tree models、Boosting、 Committee
- 用MSC库写贪吃蛇——记我的第一个游戏
- Andrew Ng's deeplearning Course1Week3 Practice Questions(练习题)
- GIS基本概念