for 循环的本质,以及对range、list的循环的理解

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博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值