迭代器python与列表的区别_与python列表混淆:它们还是不是迭代器?

I am studying Alex Marteli's Python in a Nutshell and the book suggests that any object that has a next() method is (or at least can be used as) an iterator. It also suggests that most iterators are built by implicit or explicit calls to a method called iter.

After reading this in the book, I felt the urge to try it. I fired up a python 2.7.3 interpreter and did this:

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

>>> for number in range(0, 10):

... print x.next()

However the result was this:

Traceback (most recent call last):

File "", line 2, in

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

In confusion, I tried to study the structure of the x object via dir(x) and I noticed that it had a __iter__ function object. So I figured out that it can be used as an iterator, so long as it supports that type of interface.

So when I tried again, this time slightly differently, attempting to do this:

>>> _temp_iter = next(x)

I got this error:

Traceback (most recent call last):

File "", line 1, in

TypeError: list object is not an iterator

But how can a list NOT be an iterator, since it appears to support this interface, and can be certainly used as one in the following context:

>>> for number in x:

... print x

Could someone help me clarify this in my mind?

解决方案

They are iterable, but they are not iterators. They can be passed to iter() to get an iterator for them either implicitly (e.g. via for) or explicitly, but they are not iterators in and of themselves.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值