for 循环的本质是调用 iter()将列表等对象,转化为可迭代对象,再用_next_方法进行调用。
当for循环内会改变迭代对象时,next方法会按照索引继续##读##
简单的来说,就是如下问题
#简单的来说,如下
i=list(range(10))
for x in i:
i.remove(x)
print(i)
'''
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 8, 9]
[1, 3, 5, 7, 9]'''
remove并没能移掉所有元素,他是按位置索引读取x的
最后关于iter
class Foo:
def __init__(self,n):
self.n=n
def __iter__(self):
return self
def __next__(self):
if self.n>20:
raise StopIteration
else:
self.n+=1
return self.n
f=Foo(10)
for i in range(10): # 15会报错 stopiteration
print(f.__next__())
'''
for循环的本质:调用iter,再next方法.并阻止stopiteration.
最好再提一下range(10),其是range对象
i=range(10)
for x in i:
i.remove(x)
print(i)
'''
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[3], line 2
1 for x in i:
----> 2 i.remove(x)
3 print(i)
AttributeError: 'range' object has no attribute 'remove'
'''
参考:python--class:迭代器(iter、next方法)_python class iter函数-CSDN博客