# 实现一个range

class MyRange(collections.Iterator):
def __init__(self, bound):
self.cur = -1
self.bound = bound
def __iter__(self):
return self
def __next__(self):
if self.cur < self.bound:
self.cur += 1
return self.cur
else:
raise StopIteration


def my_range(bound):
for i in range(stop):
yield i

L = [2,3,4]
I = iter(L)
print(iter(L))
print(I is L)
print(I is iter(I))

<list_iterator object at 0x00000000021E0978>
False
True


open函数返回的已打开的文件对象，也是可以一行一行的读取，直至文件结束，那很显然，他也是可迭代对象。

f = open('myfile.txt')
print(f is iter(f))

True

f = open('myfile.txt')
print(line, end='')

hello text file
goodbyt text file
Hahahahah

f = open('myfile.txt')
for line in f:
print(line, end='')

hello text file
goodbyt text file
Hahahahah

D = {'a':1, 'b':2, 'c':3}
I = iter(D)
print(next(I))
print(next(I))
print(next(I))
print(next(I))

a
b
c
Traceback (most recent call last):
File "E:/12homework/12homework.py", line 6, in <module>
print(next(I))
StopIteration

D = {'a':1, 'b':2, 'c':3}
for k in D:
print(k)

c
a
b

D = {'a':1,'b':2,'c':3}
print(D.keys())
print(iter(D.keys()))
print(D.values())
print(iter(D.values()))
print(D.items())
print(iter(D.items()))

dict_keys(['b', 'a', 'c'])
<dict_keyiterator object at 0x0000000002202958>
dict_values([2, 1, 3])
<dict_valueiterator object at 0x0000000002202958>
dict_items([('b', 2), ('a', 1), ('c', 3)])
<dict_itemiterator object at 0x00000000022029A8>

range函数的返回值是一个可迭代对象，同理利用iter方法也可以得到他的迭代器

R = range(5)
I = iter(R)
print(R)
print(I)

range(0, 5)
<range_iterator object at 0x0000000002191A30>

enumerate方法返回的也是可迭代对象，他的迭代器就是他自身

E = enumerate('spam')
print(E)
print(iter(E))

<enumerate object at 0x00000000021F2558>
<enumerate object at 0x00000000021F2558>


print(list(enumerate('spam')))
[(0, 's'), (1, 'p'), (2, 'a'), (3, 'm')] 

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120