python iterator,Python中的list和iterator有什么区别?

I am reading the book Think Python: How to think like a computer scientist, which says that in Python 3.x, dict([list of tuples]) returns an iterator instead of a list (as is the case in Python 2.7).

The book did not explain it any further, which has left me confused. In particular, I would like to know:

How are iterators and lists different, and

What is the advantage of returning an iterator over a list?

解决方案

First of all, your book is wrong (or you've misunderstood it):

>>> dict([(1, 2), (3, 4), (5, 6)])

{1: 2, 3: 4, 5: 6}

As you can see, dict([list of tuples]) returns a dictionary in both Python 2.x and 3.x.

The fundamental difference between a list and an iterator is that a list contains a number of objects in a specific order - so you can, for instance, pull one of them out from somewhere in the middle:

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> my_list

['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> my_list[3]

'd'

... whereas an iterator yields a number of objects in a specific order, often creating them on the fly as requested:

>>> my_iter = iter(range(1000000000000))

>>> my_iter

>>> next(my_iter)

0

>>> next(my_iter)

1

>>> next(my_iter)

2

I'm using next() here for demonstration purposes; in real code it's more common to iterate over an iterator with a for loop:

for x in my_iter:

# do something with x

Notice the trade-off: a list of a trillion integers would use more memory than most machines have available, which makes the iterator much more efficient ... at the cost of not being able to ask for an object somewhere in the middle:

>>> my_iter[37104]

Traceback (most recent call last):

File "", line 1, in

TypeError: 'range_iterator' object is not subscriptable

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值