iter()——迭代器

版权声明:本文为博主原创文章,如有需要,可以随意转载,请注明出处。 https://blog.csdn.net/xunye_dream/article/details/82918212

一、文件对象就是自己的迭代器,即文件有自己的__next__操作。

>>> f = open('E:\Python\hello.py')
>>> iter(f) is f
True
>>> f.__next__()
'#!/usr/bin/env python3\n'

二、列表以及多数其他内置对象,不是自身的迭代器。对于这些对象,要使用迭代器的属性,必须调用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

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/82918212