python中iterable什么意思_Python iterator, iterable有什么区别

12/23

2015

Python iterator, iterable有什么区别

An ITERABLE is:

anything that can be looped over (i.e. you can loop over a string or file)

anything that can appear on the right-side of a for-loop:for x in iterable: ...

anything you can call with iter() have it return an ITERATOR:iter(obj)

an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method suitable for indexed lookup.

An ITERATOR is:

an object with state that remembers where it is during iteration

an object with a __next__ method (Python 3; next before) that:

returns the next value in the iteration

updates the state to point at the next value

signals when it is done by raising StopIteration

an object that is self-iterable (meaning that it has an __iter__ method that returns self). (一个iterator有必要有这个方法吗?那它不就是iterable?最令人困惑的是一个iterator只能在for循环中使用一次。)

The builtin function next calls the __next__ (Python 3) or next (Python 2) method on the object passed to it.

For example:

>>> 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 complete

Traceback (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、付费专栏及课程。

余额充值