您的位置:首页 > 编程语言 > Python开发

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的,通过代码我们也可以看到提示:

<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: