l=[‘egon‘,‘liu‘,‘alex‘]
i=0
while i < len(l):
print(l[i])
i+=1
s1=‘‘
# s1.__iter__()
l=[]
# l.__iter__()
t=(1,)
# t.__iter__()
d={‘a‘:1}
# d.__iter__()
set1={1,2,3}
# set1.__iter__()
with open(‘a.txt‘,mode=‘w‘) as f:
# f.__iter__()
pass
d={‘a‘:1,‘b‘:2,‘c‘:3}
d_iterator=d.__iter__()
# print(d_iterator)
# print(d_iterator.__next__())
# print(d_iterator.__next__())
# print(d_iterator.__next__())
# print(d_iterator.__next__()) # 抛出异常StopIteration
while True:
try:
print(d_iterator.__next__())
except StopIteration:
break
print(‘====>>>>>>‘) # 在一个迭代器取值取干净的情况下,再对其取值娶不到
d_iterator=d.__iter__()
while True:
try:
print(d_iterator.__next__())
except StopIteration:
break
l=[1,2,3,4,5]
l_iterator=l.__iter__()
while True:
try:
print(l_iterator.__next__())
except StopIteration:
break
("可以转换成迭代器的对象"):内置有__iter__方法对象
可迭代对象.__iter__(): 得到迭代器对象
内置有__next__方法并且内置有__iter__方法的对象
迭代器对象.__next__():得到迭代器的下一个值
迭代器对象.__iter__():得到迭代器的本身,说白了调了跟没调一个样子
dic={‘a‘:1,‘b‘:2,‘c‘:3}
dic_iterator=dic.__iter__()
print(dic_iterator is dic_iterator.__iter__().__iter__().__iter__())
s1=‘‘
s1.__iter__()
l=[]
l.__iter__()
t=(1,)
t.__iter__()
d={‘a‘:1}
d.__iter__()
set1={1,2,3}
set1.__iter__()
with open(‘a.txt‘,mode=‘w‘) as f:
f.__iter__()
f.__next__()
# 1.d.__iter__()得到一个迭代器对象
# 2.迭代器对象.__next__()拿到一个返回值,然后将该返回值赋值给k
# 3.循环往复步骤2,直到抛出StopIteration异常for循环会捕捉异常然后结束循环
d={‘a‘:1,‘b‘:2,‘c‘:3}
for k in d:
print(k)
with open(‘a.txt‘,mode=‘rt‘,encoding=‘utf-8‘) as f:
for line in f: # f.__iter__()
print(line)
list(‘hello‘) #原理同for循环
def func():
print(‘第一次‘)
yield 1
print(‘第二次‘)
yield 2
print(‘第三次‘)
yield 3
print(‘第四次‘)
g=func()
print(g)
# 生成器就是迭代器
g.__iter__()
g.__next__()
res1=g.__next__()
print(res1)
res2=g.__next__()
print(res2)
res3=g.__next__()
print(res3)
res4=g.__next__()
len(‘aaa‘) # ‘aaa‘.__len__()
next(g) # g.__next__()
iter(可迭代对象) # 可迭代对象.__iter__()
def my_range(start,stop,step=1):
# print(‘start...‘)
while start < stop:
yield start
start+=step
# print(‘end....‘)
g=my_range(1,5,2) # 1 3
print(next(g))
print(next(g))
print(next(g))
for n in my_range(1,7,2):
print(n)
原文:https://www.cnblogs.com/x945669/p/12562016.html