我是靠谱客的博主 阳光过客,这篇文章主要介绍iter()——迭代器,现在分享给大家,希望可以做个参考。

一、文件对象就是自己的迭代器,即文件有自己的__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()——迭代器内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(116)

评论列表共有 0 条评论

立即
投稿
返回
顶部