温度转换函数是python内置函数吗_python内置函数iter()如何将python列表转换为迭代器?...

I have read my materials, which tell that a python iterator must have both __iter__ and __next__ method, but an iterable just needs __iter__. I check a list and find it has no __next__ method. When using iter() on it, it will become an iterator. This means that iter() will add a __next__ method to a list to convert it to an iterator? If yes, how does this happen?

解决方案

No. iter returns an iterator, it does not convert the list into an iterator. It doesn't modify the list at all, and certainly, the list does not get a __next__ method.

>>> x = [1,2]

>>> it = iter(x)

>>> it

>>> x.__next__

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'list' object has no attribute '__next__'

>>>

Lists are iterables, not iterators. They implement a __iter__ method, thus they are iterable:

>>> x.__iter__

But not __next__, thus they are not iterators:

>>> next(x)

Traceback (most recent call last):

File "", line 1, in

TypeError: 'list' object is not an iterator

Iterators themselves are iterable, by definition, since they implement __iter__ as well. Consider:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> it = iter(x)

>>> it

>>> it.__iter__

Most iterators should simply return themselves when you use iter on them:

>>> it2 = iter(it)

>>> it, it2

(, )

>>> it is it2

True

>>>

"Iterators are required to have an __iter__() method that returns the

iterator object itself so every iterator is also iterable and may be

used in most places where other iterables are accepted."

Note, again, they are the same iterator:

>>> next(it)

1

>>> next(it2)

2

>>> next(it)

3

>>> next(it)

4

>>> next(it2)

5

>>> list(it)

[6, 7, 8, 9]

>>> next(it2)

Traceback (most recent call last):

File "", line 1, in

StopIteration

So an iterator implements __iter__ and __next__, an iterable just means that it implements __iter__. What is returned by __iter__ is an iterator, so that must implement __next__.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值