Python - iterable 简单理解
2016-06-22 10:35
645 查看
iterable
可以iterate(迭代)的类型的参数即为iterables [即可以用for语句来循环的类型]
使用for语句,我们可以iterate每个list的元素;对一个dictionary来说,我们可以用for来iterate每个key;对一篇文章来说,我们可以用for来iterate并得到每一行的内容…
以上可见有很多类型的数据是可以iterate的,而这些对象就叫做iterable objects
#int 型因为只有一个恒定的数值,是没有办法iterate的,通过代码我们也可以看到提示:
在python里,对于所有iterable有内置函数iter(),传入iterable参数后会返回其iterator。还有另一个内置函数__next__()[在python2版本中为next()],它也可以传入一个iterable,并返回其下一个元素,如:
每次call __next__()都会返回下一个元素,如果没有更多的元素则停止迭代 提示StopIteration
可以iterate(迭代)的类型的参数即为iterables [即可以用for语句来循环的类型]
使用for语句,我们可以iterate每个list的元素;对一个dictionary来说,我们可以用for来iterate每个key;对一篇文章来说,我们可以用for来iterate并得到每一行的内容…
以上可见有很多类型的数据是可以iterate的,而这些对象就叫做iterable objects
#int 型因为只有一个恒定的数值,是没有办法iterate的,通过代码我们也可以看到提示:
<span style="font-family:Microsoft YaHei;font-size:14px;">Traceback (most recent call last): File ""C:/Users/Naomi/PycharmProjects/untitled1/tutorial_thenewboston/demo_struct.py"", line 6, in <module> a = sum(1,1) TypeError: 'int' object is not iterable </span>
在python里,对于所有iterable有内置函数iter(),传入iterable参数后会返回其iterator。还有另一个内置函数__next__()[在python2版本中为next()],它也可以传入一个iterable,并返回其下一个元素,如:
<span style="font-size:18px;">>>> a = iter([1,2,3]) >>> a <list_iterator object at 0x000001EA311D6748> >>> a.__next__() 1 >>> a.__next__() 2 >>> a.__next__() 3 >>> a.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>></span>
每次call __next__()都会返回下一个元素,如果没有更多的元素则停止迭代 提示StopIteration
相关文章推荐
- Python-SciPyStack安装(NumPy & SciPy)
- 转 python基础学习笔记(一)
- python 反编译 pyc 资料
- Python调用(运行)外部程序
- Python按行读取文件的简单实现方法
- python-crontab实现定时任务
- python的json.dumps中文问题
- python进程、线程、协程
- Python的zip函数
- 基于python的机器学习库
- Python全栈开发之11、进程和线程
- python中使用xlrd、xlwt操作excel表格详解
- Python全栈开发之目录
- python3.4学习笔记(十六) windows下面安装easy_install和pip教程
- python学习好书推荐
- python 进程和线程
- Python的不同实现
- Python从入门到PY交易,基础语法,散记(一)
- VII Python(6)基础知识(re正则表达式、MySQLdb模块)
- Python 操作 MySQL数据库