一、文件对象就是自己的迭代器,即文件有自己的__next__操作。
>>> f = open('E:Pythonhello.py')
>>> iter(f) is f
True
>>> f.__next__()
'#!/usr/bin/env python3n'
二、列表以及多数其他内置对象,不是自身的迭代器。对于这些对象,要使用迭代器的属性,必须调用iter操作来启动迭代。
>>> L = [1, 2, 3]
>>> iter(L) is L
False
>>> L.__next__()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
L.__next__()
AttributeError: 'list' object has no attribute '__next__'
>>> I = iter(L)
>>> I.__next__()
1
>>> next(I)
2
>>>
#========================================================================
>>> D = {'a' : 1, 'b' : 2, 'c' : 3}
>>> for key in D.keys():
print(key, D[key])
a 1
b 2
c 3
>>> I = iter(D)
>>> next(I)
'a'
>>> next(I)
'b'
>>>
>>> for key in D:
print(key, D[key])
a 1
b 2
c 3
最后
以上就是阳光过客最近收集整理的关于iter()——迭代器的全部内容,更多相关iter()——迭代器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复