python迭代器含义_迭代器、迭代器和迭代到底是什么?

下面是我在教学Python课程时使用的解释:

ITERABLE是:任何可以循环的东西(例如,您可以在字符串或文件上循环)或

可以出现在for-循环右侧的任何内容:

for x in iterable: ...或

任何你可以调用的东西

iter()它将返回一个ITERATOR:

iter(obj)或

定义

__iter__返回一个新的ITERATOR,或者它可能有一个

__getitem__方法,适用于索引查找。

ITERATOR是一个对象:如果状态记得它在迭代过程中所处的位置,

带着

__next__方法:返回迭代中的下一个值。

将状态更新为指向下一个值。

发出信号时,它是通过提高

StopIteration

这是可自我迭代的(意思是它有一个

__iter__方法返回

self).

注:这个

__next__方法在Python 3中是拼写的。

next在Python 2中,以及

内建函数

next()调用传递给它的对象上的方法。

例如:>>> s = 'cat'      # s is an ITERABLE

# s is a str object that is immutable

# s has no state

# s has a __getitem__() method >>> t = iter(s)    # t is an ITERATOR

# t has state (it starts by pointing at the "c"

# t has a next() method and an __iter__() method>>> next(t)

# the next() function returns the next value and advances the state'c'>>> next(t)

# the next() function returns the next value and advances'a'>>> next(t)

# the next() function returns the next value and advances't'>>> next(t)

# next() raises StopIteration to signal that iteration is completeTraceback (most recent call last):...

StopIteration>>> iter(t) is t   # the iterator is self-iterable

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值